1 //===-- SourceFile.cpp - SourceFile implementation for the debugger -------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the SourceFile class for the LLVM debugger.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Debugger/SourceFile.h"
19 /// readFile - Load Filename
21 void SourceFile::readFile() {
23 if (!File.map(&ErrMsg))
27 /// calculateLineOffsets - Compute the LineOffset vector for the current file.
29 void SourceFile::calculateLineOffsets() const {
30 assert(LineOffset.empty() && "Line offsets already computed!");
31 const char *BufPtr = File.charBase();
32 const char *FileStart = BufPtr;
33 const char *FileEnd = FileStart + File.size();
35 LineOffset.push_back(BufPtr-FileStart);
37 // Scan until we get to a newline.
38 while (BufPtr != FileEnd && *BufPtr != '\n' && *BufPtr != '\r')
41 if (BufPtr != FileEnd) {
42 ++BufPtr; // Skip over the \n or \r
43 if (BufPtr[-1] == '\r' && BufPtr != FileEnd && BufPtr[0] == '\n')
44 ++BufPtr; // Skip over dos/windows style \r\n's
46 } while (BufPtr != FileEnd);
50 /// getSourceLine - Given a line number, return the start and end of the line
51 /// in the file. If the line number is invalid, or if the file could not be
52 /// loaded, null pointers are returned for the start and end of the file. Note
53 /// that line numbers start with 0, not 1.
54 void SourceFile::getSourceLine(unsigned LineNo, const char *&LineStart,
55 const char *&LineEnd) const {
56 LineStart = LineEnd = 0;
57 if (!File.isMapped()) return; // Couldn't load file, return null pointers
58 if (LineOffset.empty()) calculateLineOffsets();
60 // Asking for an out-of-range line number?
61 if (LineNo >= LineOffset.size()) return;
63 // Otherwise, they are asking for a valid line, which we can fulfill.
64 LineStart = File.charBase()+LineOffset[LineNo];
66 if (LineNo+1 < LineOffset.size())
67 LineEnd = File.charBase()+LineOffset[LineNo+1];
69 LineEnd = File.charBase() + File.size();
71 // If the line ended with a newline, strip it off.
72 while (LineEnd != LineStart && (LineEnd[-1] == '\n' || LineEnd[-1] == '\r'))
75 assert(LineEnd >= LineStart && "We somehow got our pointers swizzled!");