xref: /netbsd-src/external/bsd/elftosb/dist/elftosb2/ConversionController.cpp (revision 993229b6fea628ff8b1fa09146c80b0cfb2768eb)
1*993229b6Sjkunz /*
2*993229b6Sjkunz  * File:	ConversionController.cpp
3*993229b6Sjkunz  *
4*993229b6Sjkunz  * Copyright (c) Freescale Semiconductor, Inc. All rights reserved.
5*993229b6Sjkunz  * See included license file for license details.
6*993229b6Sjkunz  */
7*993229b6Sjkunz 
8*993229b6Sjkunz #include "ConversionController.h"
9*993229b6Sjkunz #include <stdexcept>
10*993229b6Sjkunz #include "EvalContext.h"
11*993229b6Sjkunz #include "ElftosbErrors.h"
12*993229b6Sjkunz #include "GlobMatcher.h"
13*993229b6Sjkunz #include "ExcludesListMatcher.h"
14*993229b6Sjkunz #include "BootImageGenerator.h"
15*993229b6Sjkunz #include "EncoreBootImageGenerator.h"
16*993229b6Sjkunz #include "Logging.h"
17*993229b6Sjkunz #include "OptionDictionary.h"
18*993229b6Sjkunz #include "format_string.h"
19*993229b6Sjkunz #include "SearchPath.h"
20*993229b6Sjkunz #include "DataSourceImager.h"
21*993229b6Sjkunz #include "IVTDataSource.h"
22*993229b6Sjkunz #include <algorithm>
23*993229b6Sjkunz 
24*993229b6Sjkunz //! Set to 1 to cause the ConversionController to print information about
25*993229b6Sjkunz //! the values that it processes (options, constants, etc.).
26*993229b6Sjkunz #define PRINT_VALUES 1
27*993229b6Sjkunz 
28*993229b6Sjkunz using namespace elftosb;
29*993229b6Sjkunz 
30*993229b6Sjkunz // Define the parser function prototype;
31*993229b6Sjkunz extern int yyparse(ElftosbLexer * lexer, CommandFileASTNode ** resultAST);
32*993229b6Sjkunz 
33*993229b6Sjkunz bool elftosb::g_enableHABSupport = false;
34*993229b6Sjkunz 
ConversionController()35*993229b6Sjkunz ConversionController::ConversionController()
36*993229b6Sjkunz :	OptionDictionary(),
37*993229b6Sjkunz 	m_commandFilePath(),
38*993229b6Sjkunz 	m_ast(),
39*993229b6Sjkunz 	m_defaultSource(0)
40*993229b6Sjkunz {
41*993229b6Sjkunz 	m_context.setSourceFileManager(this);
42*993229b6Sjkunz }
43*993229b6Sjkunz 
~ConversionController()44*993229b6Sjkunz ConversionController::~ConversionController()
45*993229b6Sjkunz {
46*993229b6Sjkunz 	// clean up sources
47*993229b6Sjkunz 	source_map_t::iterator it = m_sources.begin();
48*993229b6Sjkunz 	for (; it != m_sources.end(); ++it)
49*993229b6Sjkunz 	{
50*993229b6Sjkunz 		if (it->second)
51*993229b6Sjkunz 		{
52*993229b6Sjkunz 			delete it->second;
53*993229b6Sjkunz 		}
54*993229b6Sjkunz 	}
55*993229b6Sjkunz }
56*993229b6Sjkunz 
setCommandFilePath(const std::string & path)57*993229b6Sjkunz void ConversionController::setCommandFilePath(const std::string & path)
58*993229b6Sjkunz {
59*993229b6Sjkunz 	m_commandFilePath = new std::string(path);
60*993229b6Sjkunz }
61*993229b6Sjkunz 
62*993229b6Sjkunz //! The paths provided to this method are added to an array and accessed with the
63*993229b6Sjkunz //! "extern(N)" notation in the command file. So the path provided in the third
64*993229b6Sjkunz //! call to addExternalFilePath() will be found with N=2 in the source definition.
addExternalFilePath(const std::string & path)65*993229b6Sjkunz void ConversionController::addExternalFilePath(const std::string & path)
66*993229b6Sjkunz {
67*993229b6Sjkunz 	m_externPaths.push_back(path);
68*993229b6Sjkunz }
69*993229b6Sjkunz 
hasSourceFile(const std::string & name)70*993229b6Sjkunz bool ConversionController::hasSourceFile(const std::string & name)
71*993229b6Sjkunz {
72*993229b6Sjkunz 	return m_sources.find(name) != m_sources.end();
73*993229b6Sjkunz }
74*993229b6Sjkunz 
getSourceFile(const std::string & name)75*993229b6Sjkunz SourceFile * ConversionController::getSourceFile(const std::string & name)
76*993229b6Sjkunz {
77*993229b6Sjkunz 	if (!hasSourceFile(name))
78*993229b6Sjkunz 	{
79*993229b6Sjkunz 		return NULL;
80*993229b6Sjkunz 	}
81*993229b6Sjkunz 
82*993229b6Sjkunz 	return m_sources[name];
83*993229b6Sjkunz }
84*993229b6Sjkunz 
getDefaultSourceFile()85*993229b6Sjkunz SourceFile * ConversionController::getDefaultSourceFile()
86*993229b6Sjkunz {
87*993229b6Sjkunz 	return m_defaultSource;
88*993229b6Sjkunz }
89*993229b6Sjkunz 
90*993229b6Sjkunz //! These steps are executed while running this method:
91*993229b6Sjkunz //!		- The command file is parsed into an abstract syntax tree.
92*993229b6Sjkunz //!		- The list of options is extracted.
93*993229b6Sjkunz //!		- Constant expressions are evaluated.
94*993229b6Sjkunz //!		- The list of source files is extracted and source file objects created.
95*993229b6Sjkunz //!		- Section definitions are extracted.
96*993229b6Sjkunz //!
97*993229b6Sjkunz //! This method does not produce any output. It processes the input files and
98*993229b6Sjkunz //! builds a representation of the output in memory. Use the generateOutput() method
99*993229b6Sjkunz //! to produce a BootImage object after this method returns.
100*993229b6Sjkunz //!
101*993229b6Sjkunz //! \note This method is \e not reentrant. And in fact, the whole class is not designed
102*993229b6Sjkunz //!		to be reentrant.
103*993229b6Sjkunz //!
104*993229b6Sjkunz //! \exception std::runtime_error Any number of problems will cause this exception to
105*993229b6Sjkunz //!		be thrown.
106*993229b6Sjkunz //!
107*993229b6Sjkunz //! \see parseCommandFile()
108*993229b6Sjkunz //! \see processOptions()
109*993229b6Sjkunz //! \see processConstants()
110*993229b6Sjkunz //! \see processSources()
111*993229b6Sjkunz //! \see processSections()
run()112*993229b6Sjkunz void ConversionController::run()
113*993229b6Sjkunz {
114*993229b6Sjkunz #if PRINT_VALUES
115*993229b6Sjkunz 	Log::SetOutputLevel debugLevel(Logger::DEBUG2);
116*993229b6Sjkunz #endif
117*993229b6Sjkunz 
118*993229b6Sjkunz 	parseCommandFile();
119*993229b6Sjkunz 	assert(m_ast);
120*993229b6Sjkunz 
121*993229b6Sjkunz 	ListASTNode * blocks = m_ast->getBlocks();
122*993229b6Sjkunz 	if (!blocks)
123*993229b6Sjkunz 	{
124*993229b6Sjkunz 		throw std::runtime_error("command file has no blocks");
125*993229b6Sjkunz 	}
126*993229b6Sjkunz 
127*993229b6Sjkunz 	ListASTNode::iterator it = blocks->begin();
128*993229b6Sjkunz 	for (; it != blocks->end(); ++it)
129*993229b6Sjkunz 	{
130*993229b6Sjkunz 		ASTNode * node = *it;
131*993229b6Sjkunz 
132*993229b6Sjkunz 		// Handle an options block.
133*993229b6Sjkunz 		OptionsBlockASTNode * options = dynamic_cast<OptionsBlockASTNode *>(node);
134*993229b6Sjkunz 		if (options)
135*993229b6Sjkunz 		{
136*993229b6Sjkunz 			processOptions(options->getOptions());
137*993229b6Sjkunz 			continue;
138*993229b6Sjkunz 		}
139*993229b6Sjkunz 
140*993229b6Sjkunz 		// Handle a constants block.
141*993229b6Sjkunz 		ConstantsBlockASTNode * constants = dynamic_cast<ConstantsBlockASTNode *>(node);
142*993229b6Sjkunz 		if (constants)
143*993229b6Sjkunz 		{
144*993229b6Sjkunz 			processConstants(constants->getConstants());
145*993229b6Sjkunz 			continue;
146*993229b6Sjkunz 		}
147*993229b6Sjkunz 
148*993229b6Sjkunz 		// Handle a sources block.
149*993229b6Sjkunz 		SourcesBlockASTNode * sources = dynamic_cast<SourcesBlockASTNode *>(node);
150*993229b6Sjkunz 		if (sources)
151*993229b6Sjkunz 		{
152*993229b6Sjkunz 			processSources(sources->getSources());
153*993229b6Sjkunz 		}
154*993229b6Sjkunz 	}
155*993229b6Sjkunz 
156*993229b6Sjkunz 	processSections(m_ast->getSections());
157*993229b6Sjkunz }
158*993229b6Sjkunz 
159*993229b6Sjkunz //! Opens the command file and runs it through the lexer and parser. The resulting
160*993229b6Sjkunz //! abstract syntax tree is held in the m_ast member variable. After parsing, the
161*993229b6Sjkunz //! command file is closed.
162*993229b6Sjkunz //!
163*993229b6Sjkunz //! \exception std::runtime_error Several problems will cause this exception to be
164*993229b6Sjkunz //!		raised, including an unspecified command file path or an error opening the
165*993229b6Sjkunz //!		file.
parseCommandFile()166*993229b6Sjkunz void ConversionController::parseCommandFile()
167*993229b6Sjkunz {
168*993229b6Sjkunz 	if (!m_commandFilePath)
169*993229b6Sjkunz 	{
170*993229b6Sjkunz 		throw std::runtime_error("no command file path was provided");
171*993229b6Sjkunz 	}
172*993229b6Sjkunz 
173*993229b6Sjkunz 	// Search for command file
174*993229b6Sjkunz 	std::string actualPath;
175*993229b6Sjkunz 	bool found = PathSearcher::getGlobalSearcher().search(*m_commandFilePath, PathSearcher::kFindFile, true, actualPath);
176*993229b6Sjkunz 	if (!found)
177*993229b6Sjkunz 	{
178*993229b6Sjkunz 		throw runtime_error(format_string("unable to find command file %s\n", m_commandFilePath->c_str()));
179*993229b6Sjkunz 	}
180*993229b6Sjkunz 
181*993229b6Sjkunz 	// open command file
182*993229b6Sjkunz 	std::ifstream commandFile(actualPath.c_str(), ios_base::in | ios_base::binary);
183*993229b6Sjkunz 	if (!commandFile.is_open())
184*993229b6Sjkunz 	{
185*993229b6Sjkunz 		throw std::runtime_error("could not open command file");
186*993229b6Sjkunz 	}
187*993229b6Sjkunz 
188*993229b6Sjkunz 	try
189*993229b6Sjkunz 	{
190*993229b6Sjkunz 		// create lexer instance
191*993229b6Sjkunz 		ElftosbLexer lexer(commandFile);
192*993229b6Sjkunz //		testLexer(lexer);
193*993229b6Sjkunz 
194*993229b6Sjkunz 		CommandFileASTNode * ast = NULL;
195*993229b6Sjkunz 		int result = yyparse(&lexer, &ast);
196*993229b6Sjkunz 		m_ast = ast;
197*993229b6Sjkunz 
198*993229b6Sjkunz 		// check results
199*993229b6Sjkunz 		if (result || !m_ast)
200*993229b6Sjkunz 		{
201*993229b6Sjkunz 			throw std::runtime_error("failed to parse command file");
202*993229b6Sjkunz 		}
203*993229b6Sjkunz 
204*993229b6Sjkunz 		// dump AST
205*993229b6Sjkunz //		m_ast->printTree(0);
206*993229b6Sjkunz 
207*993229b6Sjkunz 		// close command file
208*993229b6Sjkunz 		commandFile.close();
209*993229b6Sjkunz 	}
210*993229b6Sjkunz 	catch (...)
211*993229b6Sjkunz 	{
212*993229b6Sjkunz 		// close command file
213*993229b6Sjkunz 		commandFile.close();
214*993229b6Sjkunz 
215*993229b6Sjkunz 		// rethrow exception
216*993229b6Sjkunz 		throw;
217*993229b6Sjkunz 	}
218*993229b6Sjkunz }
219*993229b6Sjkunz 
220*993229b6Sjkunz //! Iterates over the option definition AST nodes. elftosb::Value objects are created for
221*993229b6Sjkunz //! each option value and added to the option dictionary.
222*993229b6Sjkunz //!
223*993229b6Sjkunz //! \exception std::runtime_error Various errors will cause this exception to be thrown. These
224*993229b6Sjkunz //!		include AST nodes being an unexpected type or expression not evaluating to integers.
processOptions(ListASTNode * options)225*993229b6Sjkunz void ConversionController::processOptions(ListASTNode * options)
226*993229b6Sjkunz {
227*993229b6Sjkunz 	if (!options)
228*993229b6Sjkunz 	{
229*993229b6Sjkunz 		return;
230*993229b6Sjkunz 	}
231*993229b6Sjkunz 
232*993229b6Sjkunz 	ListASTNode::iterator it = options->begin();
233*993229b6Sjkunz 	for (; it != options->end(); ++it)
234*993229b6Sjkunz 	{
235*993229b6Sjkunz 		std::string ident;
236*993229b6Sjkunz 		Value * value = convertAssignmentNodeToValue(*it, ident);
237*993229b6Sjkunz 
238*993229b6Sjkunz 		// check if this option has already been set
239*993229b6Sjkunz 		if (hasOption(ident))
240*993229b6Sjkunz 		{
241*993229b6Sjkunz 			throw semantic_error(format_string("line %d: option already set", (*it)->getFirstLine()));
242*993229b6Sjkunz 		}
243*993229b6Sjkunz 
244*993229b6Sjkunz 		// now save the option value in our map
245*993229b6Sjkunz 		if (value)
246*993229b6Sjkunz 		{
247*993229b6Sjkunz 			setOption(ident, value);
248*993229b6Sjkunz 		}
249*993229b6Sjkunz 	}
250*993229b6Sjkunz }
251*993229b6Sjkunz 
252*993229b6Sjkunz //! Scans the constant definition AST nodes, evaluates expression nodes by calling their
253*993229b6Sjkunz //! elftosb::ExprASTNode::reduce() method, and updates the evaluation context member so
254*993229b6Sjkunz //! those constant values can be used in other expressions.
255*993229b6Sjkunz //!
256*993229b6Sjkunz //! \exception std::runtime_error Various errors will cause this exception to be thrown. These
257*993229b6Sjkunz //!		include AST nodes being an unexpected type or expression not evaluating to integers.
processConstants(ListASTNode * constants)258*993229b6Sjkunz void ConversionController::processConstants(ListASTNode * constants)
259*993229b6Sjkunz {
260*993229b6Sjkunz 	if (!constants)
261*993229b6Sjkunz 	{
262*993229b6Sjkunz 		return;
263*993229b6Sjkunz 	}
264*993229b6Sjkunz 
265*993229b6Sjkunz 	ListASTNode::iterator it = constants->begin();
266*993229b6Sjkunz 	for (; it != constants->end(); ++it)
267*993229b6Sjkunz 	{
268*993229b6Sjkunz 		std::string ident;
269*993229b6Sjkunz 		Value * value = convertAssignmentNodeToValue(*it, ident);
270*993229b6Sjkunz 
271*993229b6Sjkunz 		SizedIntegerValue * intValue = dynamic_cast<SizedIntegerValue*>(value);
272*993229b6Sjkunz 		if (!intValue)
273*993229b6Sjkunz 		{
274*993229b6Sjkunz 			throw semantic_error(format_string("line %d: constant value is an invalid type", (*it)->getFirstLine()));
275*993229b6Sjkunz 		}
276*993229b6Sjkunz 
277*993229b6Sjkunz //#if PRINT_VALUES
278*993229b6Sjkunz //		Log::log("constant ");
279*993229b6Sjkunz //		printIntConstExpr(ident, intValue);
280*993229b6Sjkunz //#endif
281*993229b6Sjkunz 
282*993229b6Sjkunz 		// record this constant's value in the evaluation context
283*993229b6Sjkunz 		m_context.setVariable(ident, intValue->getValue(), intValue->getWordSize());
284*993229b6Sjkunz 	}
285*993229b6Sjkunz }
286*993229b6Sjkunz 
287*993229b6Sjkunz //! \exception std::runtime_error Various errors will cause this exception to be thrown. These
288*993229b6Sjkunz //!		include AST nodes being an unexpected type or expression not evaluating to integers.
289*993229b6Sjkunz //!
290*993229b6Sjkunz //! \todo Handle freeing of dict if an exception occurs.
processSources(ListASTNode * sources)291*993229b6Sjkunz void ConversionController::processSources(ListASTNode * sources)
292*993229b6Sjkunz {
293*993229b6Sjkunz 	if (!sources)
294*993229b6Sjkunz 	{
295*993229b6Sjkunz 		return;
296*993229b6Sjkunz 	}
297*993229b6Sjkunz 
298*993229b6Sjkunz 	ListASTNode::iterator it = sources->begin();
299*993229b6Sjkunz 	for (; it != sources->end(); ++it)
300*993229b6Sjkunz 	{
301*993229b6Sjkunz 		SourceDefASTNode * node = dynamic_cast<SourceDefASTNode*>(*it);
302*993229b6Sjkunz 		if (!node)
303*993229b6Sjkunz 		{
304*993229b6Sjkunz 			throw semantic_error(format_string("line %d: source definition node is an unexpected type", node->getFirstLine()));
305*993229b6Sjkunz 		}
306*993229b6Sjkunz 
307*993229b6Sjkunz 		// get source name and check if it has already been defined
308*993229b6Sjkunz 		std::string * name = node->getName();
309*993229b6Sjkunz 		if (m_sources.find(*name) != m_sources.end())
310*993229b6Sjkunz 		{
311*993229b6Sjkunz 			// can't define a source multiple times
312*993229b6Sjkunz 			throw semantic_error(format_string("line %d: source already defined", node->getFirstLine()));
313*993229b6Sjkunz 		}
314*993229b6Sjkunz 
315*993229b6Sjkunz 		// convert attributes into an option dict
316*993229b6Sjkunz 		OptionDictionary * dict = new OptionDictionary(this);
317*993229b6Sjkunz 		ListASTNode * attrsNode = node->getAttributes();
318*993229b6Sjkunz 		if (attrsNode)
319*993229b6Sjkunz 		{
320*993229b6Sjkunz 			ListASTNode::iterator attrIt = attrsNode->begin();
321*993229b6Sjkunz 			for (; attrIt != attrsNode->end(); ++attrIt)
322*993229b6Sjkunz 			{
323*993229b6Sjkunz 				std::string ident;
324*993229b6Sjkunz 				Value * value = convertAssignmentNodeToValue(*attrIt, ident);
325*993229b6Sjkunz 				dict->setOption(ident, value);
326*993229b6Sjkunz 			}
327*993229b6Sjkunz 		}
328*993229b6Sjkunz 
329*993229b6Sjkunz 		// figure out which type of source definition this is
330*993229b6Sjkunz 		PathSourceDefASTNode * pathNode = dynamic_cast<PathSourceDefASTNode*>(node);
331*993229b6Sjkunz 		ExternSourceDefASTNode * externNode = dynamic_cast<ExternSourceDefASTNode*>(node);
332*993229b6Sjkunz 		SourceFile * file = NULL;
333*993229b6Sjkunz 
334*993229b6Sjkunz 		if (pathNode)
335*993229b6Sjkunz 		{
336*993229b6Sjkunz 			// explicit path
337*993229b6Sjkunz 			std::string * path = pathNode->getPath();
338*993229b6Sjkunz 
339*993229b6Sjkunz #if PRINT_VALUES
340*993229b6Sjkunz 			Log::log("source %s => path(%s)\n", name->c_str(), path->c_str());
341*993229b6Sjkunz #endif
342*993229b6Sjkunz 
343*993229b6Sjkunz 			try
344*993229b6Sjkunz 			{
345*993229b6Sjkunz 				file = SourceFile::openFile(*path);
346*993229b6Sjkunz 			}
347*993229b6Sjkunz 			catch (...)
348*993229b6Sjkunz 			{
349*993229b6Sjkunz 				// file doesn't exist
350*993229b6Sjkunz 				Log::log(Logger::INFO2, "failed to open source file: %s (ignoring for now)\n", path->c_str());
351*993229b6Sjkunz 				m_failedSources.push_back(*name);
352*993229b6Sjkunz 			}
353*993229b6Sjkunz 		}
354*993229b6Sjkunz 		else if (externNode)
355*993229b6Sjkunz 		{
356*993229b6Sjkunz 			// externally provided path
357*993229b6Sjkunz 			ExprASTNode * expr = externNode->getSourceNumberExpr()->reduce(m_context);
358*993229b6Sjkunz 			IntConstExprASTNode * intConst = dynamic_cast<IntConstExprASTNode*>(expr);
359*993229b6Sjkunz 			if (!intConst)
360*993229b6Sjkunz 			{
361*993229b6Sjkunz 				throw semantic_error(format_string("line %d: expression didn't evaluate to an integer", expr->getFirstLine()));
362*993229b6Sjkunz 			}
363*993229b6Sjkunz 
364*993229b6Sjkunz 			uint32_t externalFileNumber = static_cast<uint32_t>(intConst->getValue());
365*993229b6Sjkunz 
366*993229b6Sjkunz 			// make sure the extern number is valid
367*993229b6Sjkunz 			if (externalFileNumber >= 0 && externalFileNumber < m_externPaths.size())
368*993229b6Sjkunz 			{
369*993229b6Sjkunz 
370*993229b6Sjkunz #if PRINT_VALUES
371*993229b6Sjkunz 			Log::log("source %s => extern(%d=%s)\n", name->c_str(), externalFileNumber, m_externPaths[externalFileNumber].c_str());
372*993229b6Sjkunz #endif
373*993229b6Sjkunz 
374*993229b6Sjkunz 				try
375*993229b6Sjkunz 				{
376*993229b6Sjkunz 					file = SourceFile::openFile(m_externPaths[externalFileNumber]);
377*993229b6Sjkunz 				}
378*993229b6Sjkunz 				catch (...)
379*993229b6Sjkunz 				{
380*993229b6Sjkunz 					Log::log(Logger::INFO2, "failed to open source file: %s (ignoring for now)\n", m_externPaths[externalFileNumber].c_str());
381*993229b6Sjkunz 					m_failedSources.push_back(*name);
382*993229b6Sjkunz 				}
383*993229b6Sjkunz 			}
384*993229b6Sjkunz 		}
385*993229b6Sjkunz 		else
386*993229b6Sjkunz 		{
387*993229b6Sjkunz 			throw semantic_error(format_string("line %d: unexpected source definition node type", node->getFirstLine()));
388*993229b6Sjkunz 		}
389*993229b6Sjkunz 
390*993229b6Sjkunz 		if (file)
391*993229b6Sjkunz 		{
392*993229b6Sjkunz 			// set options
393*993229b6Sjkunz 			file->setOptions(dict);
394*993229b6Sjkunz 
395*993229b6Sjkunz 			// stick the file object in the source map
396*993229b6Sjkunz 			m_sources[*name] = file;
397*993229b6Sjkunz 		}
398*993229b6Sjkunz 	}
399*993229b6Sjkunz }
400*993229b6Sjkunz 
processSections(ListASTNode * sections)401*993229b6Sjkunz void ConversionController::processSections(ListASTNode * sections)
402*993229b6Sjkunz {
403*993229b6Sjkunz 	if (!sections)
404*993229b6Sjkunz 	{
405*993229b6Sjkunz 		Log::log(Logger::WARNING, "warning: no sections were defined in command file");
406*993229b6Sjkunz 		return;
407*993229b6Sjkunz 	}
408*993229b6Sjkunz 
409*993229b6Sjkunz 	ListASTNode::iterator it = sections->begin();
410*993229b6Sjkunz 	for (; it != sections->end(); ++it)
411*993229b6Sjkunz 	{
412*993229b6Sjkunz 		SectionContentsASTNode * node = dynamic_cast<SectionContentsASTNode*>(*it);
413*993229b6Sjkunz 		if (!node)
414*993229b6Sjkunz 		{
415*993229b6Sjkunz 			throw semantic_error(format_string("line %d: section definition is unexpected type", node->getFirstLine()));
416*993229b6Sjkunz 		}
417*993229b6Sjkunz 
418*993229b6Sjkunz 		// evaluate section number
419*993229b6Sjkunz 		ExprASTNode * idExpr = node->getSectionNumberExpr()->reduce(m_context);
420*993229b6Sjkunz 		IntConstExprASTNode * idConst = dynamic_cast<IntConstExprASTNode*>(idExpr);
421*993229b6Sjkunz 		if (!idConst)
422*993229b6Sjkunz 		{
423*993229b6Sjkunz 			throw semantic_error(format_string("line %d: section number did not evaluate to an integer", idExpr->getFirstLine()));
424*993229b6Sjkunz 		}
425*993229b6Sjkunz 		uint32_t sectionID = idConst->getValue();
426*993229b6Sjkunz 
427*993229b6Sjkunz 		// Create options context for this section. The options context has the
428*993229b6Sjkunz 		// conversion controller as its parent context so it will inherit global options.
429*993229b6Sjkunz 		// The context will be set in the section after the section is created below.
430*993229b6Sjkunz 		OptionDictionary * optionsDict = new OptionDictionary(this);
431*993229b6Sjkunz 		ListASTNode * attrsNode = node->getOptions();
432*993229b6Sjkunz 		if (attrsNode)
433*993229b6Sjkunz 		{
434*993229b6Sjkunz 			ListASTNode::iterator attrIt = attrsNode->begin();
435*993229b6Sjkunz 			for (; attrIt != attrsNode->end(); ++attrIt)
436*993229b6Sjkunz 			{
437*993229b6Sjkunz 				std::string ident;
438*993229b6Sjkunz 				Value * value = convertAssignmentNodeToValue(*attrIt, ident);
439*993229b6Sjkunz 				optionsDict->setOption(ident, value);
440*993229b6Sjkunz 			}
441*993229b6Sjkunz 		}
442*993229b6Sjkunz 
443*993229b6Sjkunz 		// Now create the actual section object based on its type.
444*993229b6Sjkunz 		OutputSection * outputSection = NULL;
445*993229b6Sjkunz 		BootableSectionContentsASTNode * bootableSection;
446*993229b6Sjkunz 		DataSectionContentsASTNode * dataSection;
447*993229b6Sjkunz 		if (bootableSection = dynamic_cast<BootableSectionContentsASTNode*>(node))
448*993229b6Sjkunz 		{
449*993229b6Sjkunz 			// process statements into a sequence of operations
450*993229b6Sjkunz 			ListASTNode * statements = bootableSection->getStatements();
451*993229b6Sjkunz 			OperationSequence * sequence = convertStatementList(statements);
452*993229b6Sjkunz 
453*993229b6Sjkunz #if 0
454*993229b6Sjkunz 			Log::log("section ID = %d\n", sectionID);
455*993229b6Sjkunz 			statements->printTree(0);
456*993229b6Sjkunz 
457*993229b6Sjkunz 			Log::log("sequence has %d operations\n", sequence->getCount());
458*993229b6Sjkunz 			OperationSequence::iterator_t it = sequence->begin();
459*993229b6Sjkunz 			for (; it != sequence->end(); ++it)
460*993229b6Sjkunz 			{
461*993229b6Sjkunz 				Operation * op = *it;
462*993229b6Sjkunz 				Log::log("op = %p\n", op);
463*993229b6Sjkunz 			}
464*993229b6Sjkunz #endif
465*993229b6Sjkunz 
466*993229b6Sjkunz 			// create the output section and add it to the list
467*993229b6Sjkunz 			OperationSequenceSection * opSection = new OperationSequenceSection(sectionID);
468*993229b6Sjkunz 			opSection->setOptions(optionsDict);
469*993229b6Sjkunz 			opSection->getSequence() += sequence;
470*993229b6Sjkunz 			outputSection = opSection;
471*993229b6Sjkunz 		}
472*993229b6Sjkunz 		else if (dataSection = dynamic_cast<DataSectionContentsASTNode*>(node))
473*993229b6Sjkunz 		{
474*993229b6Sjkunz 			outputSection = convertDataSection(dataSection, sectionID, optionsDict);
475*993229b6Sjkunz 		}
476*993229b6Sjkunz 		else
477*993229b6Sjkunz 		{
478*993229b6Sjkunz 			throw semantic_error(format_string("line %d: unexpected section contents type", node->getFirstLine()));
479*993229b6Sjkunz 		}
480*993229b6Sjkunz 
481*993229b6Sjkunz 		if (outputSection)
482*993229b6Sjkunz 		{
483*993229b6Sjkunz 			m_outputSections.push_back(outputSection);
484*993229b6Sjkunz 		}
485*993229b6Sjkunz 	}
486*993229b6Sjkunz }
487*993229b6Sjkunz 
488*993229b6Sjkunz //! Creates an instance of BinaryDataSection from the AST node passed in the
489*993229b6Sjkunz //! \a dataSection parameter. The section-specific options for this node will
490*993229b6Sjkunz //! have already been converted into an OptionDictionary, the one passed in
491*993229b6Sjkunz //! the \a optionsDict parameter.
492*993229b6Sjkunz //!
493*993229b6Sjkunz //! The \a dataSection node will have as its contents one of the AST node
494*993229b6Sjkunz //! classes that represents a source of data. The member function
495*993229b6Sjkunz //! createSourceFromNode() is used to convert this AST node into an
496*993229b6Sjkunz //! instance of a DataSource subclass. Then the method imageDataSource()
497*993229b6Sjkunz //! converts the segments of the DataSource into a raw binary buffer that
498*993229b6Sjkunz //! becomes the contents of the BinaryDataSection this is returned.
499*993229b6Sjkunz //!
500*993229b6Sjkunz //! \param dataSection The AST node for the data section.
501*993229b6Sjkunz //! \param sectionID Unique tag value the user has assigned to this section.
502*993229b6Sjkunz //! \param optionsDict Options that apply only to this section. This dictionary
503*993229b6Sjkunz //!		will be assigned as the options dictionary for the resulting section
504*993229b6Sjkunz //!		object. Its parent is the conversion controller itself.
505*993229b6Sjkunz //! \return An instance of BinaryDataSection. Its contents are a contiguous
506*993229b6Sjkunz //!		binary representation of the contents of \a dataSection.
convertDataSection(DataSectionContentsASTNode * dataSection,uint32_t sectionID,OptionDictionary * optionsDict)507*993229b6Sjkunz OutputSection * ConversionController::convertDataSection(DataSectionContentsASTNode * dataSection, uint32_t sectionID, OptionDictionary * optionsDict)
508*993229b6Sjkunz {
509*993229b6Sjkunz 	// Create a data source from the section contents AST node.
510*993229b6Sjkunz 	ASTNode * contents = dataSection->getContents();
511*993229b6Sjkunz 	DataSource * dataSource = createSourceFromNode(contents);
512*993229b6Sjkunz 
513*993229b6Sjkunz 	// Convert the data source to a raw buffer.
514*993229b6Sjkunz 	DataSourceImager imager;
515*993229b6Sjkunz 	imager.addDataSource(dataSource);
516*993229b6Sjkunz 
517*993229b6Sjkunz 	// Then make a data section from the buffer.
518*993229b6Sjkunz 	BinaryDataSection * resultSection = new BinaryDataSection(sectionID);
519*993229b6Sjkunz 	resultSection->setOptions(optionsDict);
520*993229b6Sjkunz 	if (imager.getLength())
521*993229b6Sjkunz 	{
522*993229b6Sjkunz 		resultSection->setData(imager.getData(), imager.getLength());
523*993229b6Sjkunz 	}
524*993229b6Sjkunz 
525*993229b6Sjkunz 	return resultSection;
526*993229b6Sjkunz }
527*993229b6Sjkunz 
528*993229b6Sjkunz //! @param node The AST node instance for the assignment expression.
529*993229b6Sjkunz //! @param[out] ident Upon exit this string will be set the the left hand side of the
530*993229b6Sjkunz //!		assignment expression, the identifier name.
531*993229b6Sjkunz //!
532*993229b6Sjkunz //! @return An object that is a subclass of Value is returned. The specific subclass will
533*993229b6Sjkunz //!		depend on the type of the right hand side of the assignment expression whose AST
534*993229b6Sjkunz //!		node was provided in the @a node argument.
535*993229b6Sjkunz //!
536*993229b6Sjkunz //! @exception semantic_error Thrown for any error where an AST node is an unexpected type.
537*993229b6Sjkunz //!		This may be the @a node argument itself, if it is not an AssignmentASTNode. Or it
538*993229b6Sjkunz //!		may be an unexpected type for either the right or left hand side of the assignment.
539*993229b6Sjkunz //!		The message for the exception will contain a description of the error.
convertAssignmentNodeToValue(ASTNode * node,std::string & ident)540*993229b6Sjkunz Value * ConversionController::convertAssignmentNodeToValue(ASTNode * node, std::string & ident)
541*993229b6Sjkunz {
542*993229b6Sjkunz 	Value * resultValue = NULL;
543*993229b6Sjkunz 
544*993229b6Sjkunz 	// each item of the options list should be an assignment node
545*993229b6Sjkunz 	AssignmentASTNode * assignmentNode = dynamic_cast<AssignmentASTNode*>(node);
546*993229b6Sjkunz 	if (!node)
547*993229b6Sjkunz 	{
548*993229b6Sjkunz 		throw semantic_error(format_string("line %d: node is wrong type", assignmentNode->getFirstLine()));
549*993229b6Sjkunz 	}
550*993229b6Sjkunz 
551*993229b6Sjkunz 	// save the left hand side (the identifier) into ident
552*993229b6Sjkunz 	ident = *assignmentNode->getIdent();
553*993229b6Sjkunz 
554*993229b6Sjkunz 	// get the right hand side and convert it to a Value instance
555*993229b6Sjkunz 	ASTNode * valueNode = assignmentNode->getValue();
556*993229b6Sjkunz 	StringConstASTNode * str;
557*993229b6Sjkunz 	ExprASTNode * expr;
558*993229b6Sjkunz 	if (str = dynamic_cast<StringConstASTNode*>(valueNode))
559*993229b6Sjkunz 	{
560*993229b6Sjkunz 		// the option value is a string constant
561*993229b6Sjkunz 		resultValue = new StringValue(str->getString());
562*993229b6Sjkunz 
563*993229b6Sjkunz //#if PRINT_VALUES
564*993229b6Sjkunz //		Log::log("option %s => \'%s\'\n", ident->c_str(), str->getString()->c_str());
565*993229b6Sjkunz //#endif
566*993229b6Sjkunz 	}
567*993229b6Sjkunz 	else if (expr = dynamic_cast<ExprASTNode*>(valueNode))
568*993229b6Sjkunz 	{
569*993229b6Sjkunz 		ExprASTNode * reducedExpr = expr->reduce(m_context);
570*993229b6Sjkunz 		IntConstExprASTNode * intConst = dynamic_cast<IntConstExprASTNode*>(reducedExpr);
571*993229b6Sjkunz 		if (!intConst)
572*993229b6Sjkunz 		{
573*993229b6Sjkunz 			throw semantic_error(format_string("line %d: expression didn't evaluate to an integer", expr->getFirstLine()));
574*993229b6Sjkunz 		}
575*993229b6Sjkunz 
576*993229b6Sjkunz //#if PRINT_VALUES
577*993229b6Sjkunz //		Log::log("option ");
578*993229b6Sjkunz //		printIntConstExpr(*ident, intConst);
579*993229b6Sjkunz //#endif
580*993229b6Sjkunz 
581*993229b6Sjkunz 		resultValue = new SizedIntegerValue(intConst->getValue(), intConst->getSize());
582*993229b6Sjkunz 	}
583*993229b6Sjkunz 	else
584*993229b6Sjkunz 	{
585*993229b6Sjkunz 		throw semantic_error(format_string("line %d: right hand side node is an unexpected type", valueNode->getFirstLine()));
586*993229b6Sjkunz 	}
587*993229b6Sjkunz 
588*993229b6Sjkunz 	return resultValue;
589*993229b6Sjkunz }
590*993229b6Sjkunz 
591*993229b6Sjkunz //! Builds up a sequence of Operation objects that are equivalent to the
592*993229b6Sjkunz //! statements in the \a statements list. The statement list is simply iterated
593*993229b6Sjkunz //! over and the results of convertOneStatement() are used to build up
594*993229b6Sjkunz //! the final result sequence.
595*993229b6Sjkunz //!
596*993229b6Sjkunz //! \see convertOneStatement()
convertStatementList(ListASTNode * statements)597*993229b6Sjkunz OperationSequence * ConversionController::convertStatementList(ListASTNode * statements)
598*993229b6Sjkunz {
599*993229b6Sjkunz 	OperationSequence * resultSequence = new OperationSequence();
600*993229b6Sjkunz 	ListASTNode::iterator it = statements->begin();
601*993229b6Sjkunz 	for (; it != statements->end(); ++it)
602*993229b6Sjkunz 	{
603*993229b6Sjkunz 		StatementASTNode * statement = dynamic_cast<StatementASTNode*>(*it);
604*993229b6Sjkunz 		if (!statement)
605*993229b6Sjkunz 		{
606*993229b6Sjkunz 			throw semantic_error(format_string("line %d: statement node is unexpected type", (*it)->getFirstLine()));
607*993229b6Sjkunz 		}
608*993229b6Sjkunz 
609*993229b6Sjkunz 		// convert this statement and append it to the result
610*993229b6Sjkunz 		OperationSequence * sequence = convertOneStatement(statement);
611*993229b6Sjkunz 		if (sequence)
612*993229b6Sjkunz 		{
613*993229b6Sjkunz 			*resultSequence += sequence;
614*993229b6Sjkunz 		}
615*993229b6Sjkunz 	}
616*993229b6Sjkunz 
617*993229b6Sjkunz 	return resultSequence;
618*993229b6Sjkunz }
619*993229b6Sjkunz 
620*993229b6Sjkunz //! Uses C++ RTTI to identify the particular subclass of StatementASTNode that
621*993229b6Sjkunz //! the \a statement argument matches. Then the appropriate conversion method
622*993229b6Sjkunz //! is called.
623*993229b6Sjkunz //!
624*993229b6Sjkunz //! \see convertLoadStatement()
625*993229b6Sjkunz //! \see convertCallStatement()
626*993229b6Sjkunz //! \see convertFromStatement()
convertOneStatement(StatementASTNode * statement)627*993229b6Sjkunz OperationSequence * ConversionController::convertOneStatement(StatementASTNode * statement)
628*993229b6Sjkunz {
629*993229b6Sjkunz 	// see if it's a load statement
630*993229b6Sjkunz 	LoadStatementASTNode * load = dynamic_cast<LoadStatementASTNode*>(statement);
631*993229b6Sjkunz 	if (load)
632*993229b6Sjkunz 	{
633*993229b6Sjkunz 		return convertLoadStatement(load);
634*993229b6Sjkunz 	}
635*993229b6Sjkunz 
636*993229b6Sjkunz 	// see if it's a call statement
637*993229b6Sjkunz 	CallStatementASTNode * call = dynamic_cast<CallStatementASTNode*>(statement);
638*993229b6Sjkunz 	if (call)
639*993229b6Sjkunz 	{
640*993229b6Sjkunz 		return convertCallStatement(call);
641*993229b6Sjkunz 	}
642*993229b6Sjkunz 
643*993229b6Sjkunz 	// see if it's a from statement
644*993229b6Sjkunz 	FromStatementASTNode * from = dynamic_cast<FromStatementASTNode*>(statement);
645*993229b6Sjkunz 	if (from)
646*993229b6Sjkunz 	{
647*993229b6Sjkunz 		return convertFromStatement(from);
648*993229b6Sjkunz 	}
649*993229b6Sjkunz 
650*993229b6Sjkunz 	// see if it's a mode statement
651*993229b6Sjkunz 	ModeStatementASTNode * mode = dynamic_cast<ModeStatementASTNode*>(statement);
652*993229b6Sjkunz 	if (mode)
653*993229b6Sjkunz 	{
654*993229b6Sjkunz 		return convertModeStatement(mode);
655*993229b6Sjkunz 	}
656*993229b6Sjkunz 
657*993229b6Sjkunz 	// see if it's an if statement
658*993229b6Sjkunz 	IfStatementASTNode * ifStmt = dynamic_cast<IfStatementASTNode*>(statement);
659*993229b6Sjkunz 	if (ifStmt)
660*993229b6Sjkunz 	{
661*993229b6Sjkunz 		return convertIfStatement(ifStmt);
662*993229b6Sjkunz 	}
663*993229b6Sjkunz 
664*993229b6Sjkunz 	// see if it's a message statement
665*993229b6Sjkunz 	MessageStatementASTNode * messageStmt = dynamic_cast<MessageStatementASTNode*>(statement);
666*993229b6Sjkunz 	if (messageStmt)
667*993229b6Sjkunz 	{
668*993229b6Sjkunz 		// Message statements don't produce operation sequences.
669*993229b6Sjkunz 		handleMessageStatement(messageStmt);
670*993229b6Sjkunz 		return NULL;
671*993229b6Sjkunz 	}
672*993229b6Sjkunz 
673*993229b6Sjkunz 	// didn't match any of the expected statement types
674*993229b6Sjkunz 	throw semantic_error(format_string("line %d: unexpected statement type", statement->getFirstLine()));
675*993229b6Sjkunz 	return NULL;
676*993229b6Sjkunz }
677*993229b6Sjkunz 
678*993229b6Sjkunz //! Possible load data node types:
679*993229b6Sjkunz //! - StringConstASTNode
680*993229b6Sjkunz //! - ExprASTNode
681*993229b6Sjkunz //! - SourceASTNode
682*993229b6Sjkunz //! - SectionMatchListASTNode
683*993229b6Sjkunz //!
684*993229b6Sjkunz //! Possible load target node types:
685*993229b6Sjkunz //! - SymbolASTNode
686*993229b6Sjkunz //! - NaturalLocationASTNode
687*993229b6Sjkunz //! - AddressRangeASTNode
convertLoadStatement(LoadStatementASTNode * statement)688*993229b6Sjkunz OperationSequence * ConversionController::convertLoadStatement(LoadStatementASTNode * statement)
689*993229b6Sjkunz {
690*993229b6Sjkunz 	LoadOperation * op = NULL;
691*993229b6Sjkunz 
692*993229b6Sjkunz 	try
693*993229b6Sjkunz 	{
694*993229b6Sjkunz 		// build load operation from source and target
695*993229b6Sjkunz 		op = new LoadOperation();
696*993229b6Sjkunz 		op->setSource(createSourceFromNode(statement->getData()));
697*993229b6Sjkunz 		op->setTarget(createTargetFromNode(statement->getTarget()));
698*993229b6Sjkunz 		op->setDCDLoad(statement->isDCDLoad());
699*993229b6Sjkunz 
700*993229b6Sjkunz 		return new OperationSequence(op);
701*993229b6Sjkunz 	}
702*993229b6Sjkunz 	catch (...)
703*993229b6Sjkunz 	{
704*993229b6Sjkunz 		if (op)
705*993229b6Sjkunz 		{
706*993229b6Sjkunz 			delete op;
707*993229b6Sjkunz 		}
708*993229b6Sjkunz 		throw;
709*993229b6Sjkunz 	}
710*993229b6Sjkunz }
711*993229b6Sjkunz 
712*993229b6Sjkunz //! Possible call target node types:
713*993229b6Sjkunz //! - SymbolASTNode
714*993229b6Sjkunz //! - ExprASTNode
715*993229b6Sjkunz //!
716*993229b6Sjkunz //! Possible call argument node types:
717*993229b6Sjkunz //! - ExprASTNode
718*993229b6Sjkunz //! - NULL
convertCallStatement(CallStatementASTNode * statement)719*993229b6Sjkunz OperationSequence * ConversionController::convertCallStatement(CallStatementASTNode * statement)
720*993229b6Sjkunz {
721*993229b6Sjkunz 	ExecuteOperation * op = NULL;
722*993229b6Sjkunz 
723*993229b6Sjkunz 	try
724*993229b6Sjkunz 	{
725*993229b6Sjkunz 		// create operation from AST nodes
726*993229b6Sjkunz 		op = new ExecuteOperation();
727*993229b6Sjkunz 
728*993229b6Sjkunz 		bool isHAB = statement->isHAB();
729*993229b6Sjkunz 
730*993229b6Sjkunz 		op->setTarget(createTargetFromNode(statement->getTarget()));
731*993229b6Sjkunz 
732*993229b6Sjkunz 		// set argument value, which defaults to 0 if no expression was provided
733*993229b6Sjkunz 		uint32_t arg = 0;
734*993229b6Sjkunz 		ASTNode * argNode = statement->getArgument();
735*993229b6Sjkunz 		if (argNode)
736*993229b6Sjkunz 		{
737*993229b6Sjkunz 			ExprASTNode * argExprNode = dynamic_cast<ExprASTNode*>(argNode);
738*993229b6Sjkunz 			if (!argExprNode)
739*993229b6Sjkunz 			{
740*993229b6Sjkunz 				throw semantic_error(format_string("line %d: call argument is unexpected type", argNode->getFirstLine()));
741*993229b6Sjkunz 			}
742*993229b6Sjkunz 			argExprNode = argExprNode->reduce(m_context);
743*993229b6Sjkunz 			IntConstExprASTNode * intNode = dynamic_cast<IntConstExprASTNode*>(argExprNode);
744*993229b6Sjkunz 			if (!intNode)
745*993229b6Sjkunz 			{
746*993229b6Sjkunz 				throw semantic_error(format_string("line %d: call argument did not evaluate to an integer", argExprNode->getFirstLine()));
747*993229b6Sjkunz 			}
748*993229b6Sjkunz 
749*993229b6Sjkunz 			arg = intNode->getValue();
750*993229b6Sjkunz 		}
751*993229b6Sjkunz 		op->setArgument(arg);
752*993229b6Sjkunz 
753*993229b6Sjkunz 		// set call type
754*993229b6Sjkunz 		switch (statement->getCallType())
755*993229b6Sjkunz 		{
756*993229b6Sjkunz 			case CallStatementASTNode::kCallType:
757*993229b6Sjkunz 				op->setExecuteType(ExecuteOperation::kCall);
758*993229b6Sjkunz 				break;
759*993229b6Sjkunz 			case CallStatementASTNode::kJumpType:
760*993229b6Sjkunz 				op->setExecuteType(ExecuteOperation::kJump);
761*993229b6Sjkunz 				break;
762*993229b6Sjkunz 		}
763*993229b6Sjkunz 
764*993229b6Sjkunz 		// Set the HAB mode flag.
765*993229b6Sjkunz 		op->setIsHAB(isHAB);
766*993229b6Sjkunz 
767*993229b6Sjkunz 		return new OperationSequence(op);
768*993229b6Sjkunz 	}
769*993229b6Sjkunz 	catch (...)
770*993229b6Sjkunz 	{
771*993229b6Sjkunz 		// delete op and rethrow exception
772*993229b6Sjkunz 		if (op)
773*993229b6Sjkunz 		{
774*993229b6Sjkunz 			delete op;
775*993229b6Sjkunz 		}
776*993229b6Sjkunz 		throw;
777*993229b6Sjkunz 	}
778*993229b6Sjkunz }
779*993229b6Sjkunz 
780*993229b6Sjkunz //! First this method sets the default source to the source identified in
781*993229b6Sjkunz //! the from statement. Then the statements within the from block are
782*993229b6Sjkunz //! processed recursively by calling convertStatementList(). The resulting
783*993229b6Sjkunz //! operation sequence is returned.
convertFromStatement(FromStatementASTNode * statement)784*993229b6Sjkunz OperationSequence * ConversionController::convertFromStatement(FromStatementASTNode * statement)
785*993229b6Sjkunz {
786*993229b6Sjkunz 	if (m_defaultSource)
787*993229b6Sjkunz 	{
788*993229b6Sjkunz 		throw semantic_error(format_string("line %d: from statements cannot be nested", statement->getFirstLine()));
789*993229b6Sjkunz 	}
790*993229b6Sjkunz 
791*993229b6Sjkunz 	// look up source file instance
792*993229b6Sjkunz 	std::string * fromSourceName = statement->getSourceName();
793*993229b6Sjkunz 	assert(fromSourceName);
794*993229b6Sjkunz 
795*993229b6Sjkunz 	// make sure it's a valid source name
796*993229b6Sjkunz 	source_map_t::iterator sourceIt = m_sources.find(*fromSourceName);
797*993229b6Sjkunz 	if (sourceIt == m_sources.end())
798*993229b6Sjkunz 	{
799*993229b6Sjkunz 		throw semantic_error(format_string("line %d: bad source name", statement->getFirstLine()));
800*993229b6Sjkunz 	}
801*993229b6Sjkunz 
802*993229b6Sjkunz 	// set default source
803*993229b6Sjkunz 	m_defaultSource = sourceIt->second;
804*993229b6Sjkunz 	assert(m_defaultSource);
805*993229b6Sjkunz 
806*993229b6Sjkunz 	// get statements inside the from block
807*993229b6Sjkunz 	ListASTNode * fromStatements = statement->getStatements();
808*993229b6Sjkunz 	assert(fromStatements);
809*993229b6Sjkunz 
810*993229b6Sjkunz 	// produce resulting operation sequence
811*993229b6Sjkunz 	OperationSequence * result = convertStatementList(fromStatements);
812*993229b6Sjkunz 
813*993229b6Sjkunz 	// restore default source to NULL
814*993229b6Sjkunz 	m_defaultSource = NULL;
815*993229b6Sjkunz 
816*993229b6Sjkunz 	return result;
817*993229b6Sjkunz }
818*993229b6Sjkunz 
819*993229b6Sjkunz //! Evaluates the expression to get the new boot mode value. Then creates a
820*993229b6Sjkunz //! BootModeOperation object and returns an OperationSequence containing it.
821*993229b6Sjkunz //!
822*993229b6Sjkunz //! \exception elftosb::semantic_error Thrown if a semantic problem is found with
823*993229b6Sjkunz //!		the boot mode expression.
convertModeStatement(ModeStatementASTNode * statement)824*993229b6Sjkunz OperationSequence * ConversionController::convertModeStatement(ModeStatementASTNode * statement)
825*993229b6Sjkunz {
826*993229b6Sjkunz 	BootModeOperation * op = NULL;
827*993229b6Sjkunz 
828*993229b6Sjkunz 	try
829*993229b6Sjkunz 	{
830*993229b6Sjkunz 		op = new BootModeOperation();
831*993229b6Sjkunz 
832*993229b6Sjkunz 		// evaluate the boot mode expression
833*993229b6Sjkunz 		ExprASTNode * modeExprNode = statement->getModeExpr();
834*993229b6Sjkunz 		if (!modeExprNode)
835*993229b6Sjkunz 		{
836*993229b6Sjkunz 			throw semantic_error(format_string("line %d: mode statement has invalid boot mode expression", statement->getFirstLine()));
837*993229b6Sjkunz 		}
838*993229b6Sjkunz 		modeExprNode = modeExprNode->reduce(m_context);
839*993229b6Sjkunz 		IntConstExprASTNode * intNode = dynamic_cast<IntConstExprASTNode*>(modeExprNode);
840*993229b6Sjkunz 		if (!intNode)
841*993229b6Sjkunz 		{
842*993229b6Sjkunz 			throw semantic_error(format_string("line %d: boot mode did not evaluate to an integer", statement->getFirstLine()));
843*993229b6Sjkunz 		}
844*993229b6Sjkunz 
845*993229b6Sjkunz 		op->setBootMode(intNode->getValue());
846*993229b6Sjkunz 
847*993229b6Sjkunz 		return new OperationSequence(op);
848*993229b6Sjkunz 	}
849*993229b6Sjkunz 	catch (...)
850*993229b6Sjkunz 	{
851*993229b6Sjkunz 		if (op)
852*993229b6Sjkunz 		{
853*993229b6Sjkunz 			delete op;
854*993229b6Sjkunz 		}
855*993229b6Sjkunz 
856*993229b6Sjkunz 		// rethrow exception
857*993229b6Sjkunz 		throw;
858*993229b6Sjkunz 	}
859*993229b6Sjkunz }
860*993229b6Sjkunz 
861*993229b6Sjkunz //! Else branches, including else-if, are handled recursively, so there is a limit
862*993229b6Sjkunz //! on the number of them based on the stack size.
863*993229b6Sjkunz //!
864*993229b6Sjkunz //! \return Returns the operation sequence for the branch of the if statement that
865*993229b6Sjkunz //!		evaluated to true. If the statement did not have an else branch and the
866*993229b6Sjkunz //!		condition expression evaluated to false, then NULL will be returned.
867*993229b6Sjkunz //!
868*993229b6Sjkunz //! \todo Handle else branches without recursion.
convertIfStatement(IfStatementASTNode * statement)869*993229b6Sjkunz OperationSequence * ConversionController::convertIfStatement(IfStatementASTNode * statement)
870*993229b6Sjkunz {
871*993229b6Sjkunz 	// Get the if's conditional expression.
872*993229b6Sjkunz 	ExprASTNode * conditionalExpr = statement->getConditionExpr();
873*993229b6Sjkunz 	if (!conditionalExpr)
874*993229b6Sjkunz 	{
875*993229b6Sjkunz 		throw semantic_error(format_string("line %d: missing or invalid conditional expression", statement->getFirstLine()));
876*993229b6Sjkunz 	}
877*993229b6Sjkunz 
878*993229b6Sjkunz 	// Reduce the conditional to a single integer.
879*993229b6Sjkunz 	conditionalExpr = conditionalExpr->reduce(m_context);
880*993229b6Sjkunz 	IntConstExprASTNode * intNode = dynamic_cast<IntConstExprASTNode*>(conditionalExpr);
881*993229b6Sjkunz 	if (!intNode)
882*993229b6Sjkunz 	{
883*993229b6Sjkunz 		throw semantic_error(format_string("line %d: if statement conditional expression did not evaluate to an integer", statement->getFirstLine()));
884*993229b6Sjkunz 	}
885*993229b6Sjkunz 
886*993229b6Sjkunz 	// Decide which statements to further process by the conditional's boolean value.
887*993229b6Sjkunz 	if (intNode->getValue() && statement->getIfStatements())
888*993229b6Sjkunz 	{
889*993229b6Sjkunz 		return convertStatementList(statement->getIfStatements());
890*993229b6Sjkunz 	}
891*993229b6Sjkunz 	else if (statement->getElseStatements())
892*993229b6Sjkunz 	{
893*993229b6Sjkunz 		return convertStatementList(statement->getElseStatements());
894*993229b6Sjkunz 	}
895*993229b6Sjkunz 	else
896*993229b6Sjkunz 	{
897*993229b6Sjkunz 		// No else branch and the conditional was false, so there are no operations to return.
898*993229b6Sjkunz 		return NULL;
899*993229b6Sjkunz 	}
900*993229b6Sjkunz }
901*993229b6Sjkunz 
902*993229b6Sjkunz //! Message statements are executed immediately, by this method. They are
903*993229b6Sjkunz //! not converted into an abstract operation. All messages are passed through
904*993229b6Sjkunz //! substituteVariables() before being output.
905*993229b6Sjkunz //!
906*993229b6Sjkunz //! \param statement The message statement AST node object.
handleMessageStatement(MessageStatementASTNode * statement)907*993229b6Sjkunz void ConversionController::handleMessageStatement(MessageStatementASTNode * statement)
908*993229b6Sjkunz {
909*993229b6Sjkunz 	string * message = statement->getMessage();
910*993229b6Sjkunz 	if (!message)
911*993229b6Sjkunz 	{
912*993229b6Sjkunz 		throw runtime_error("message statement had no message");
913*993229b6Sjkunz 	}
914*993229b6Sjkunz 
915*993229b6Sjkunz 	smart_ptr<string> finalMessage = substituteVariables(message);
916*993229b6Sjkunz 
917*993229b6Sjkunz 	switch (statement->getType())
918*993229b6Sjkunz 	{
919*993229b6Sjkunz 		case MessageStatementASTNode::kInfo:
920*993229b6Sjkunz 			Log::log(Logger::INFO, "%s\n", finalMessage->c_str());
921*993229b6Sjkunz 			break;
922*993229b6Sjkunz 
923*993229b6Sjkunz 		case MessageStatementASTNode::kWarning:
924*993229b6Sjkunz 			Log::log(Logger::WARNING, "warning: %s\n", finalMessage->c_str());
925*993229b6Sjkunz 			break;
926*993229b6Sjkunz 
927*993229b6Sjkunz 		case MessageStatementASTNode::kError:
928*993229b6Sjkunz 			throw runtime_error(*finalMessage);
929*993229b6Sjkunz 			break;
930*993229b6Sjkunz 	}
931*993229b6Sjkunz }
932*993229b6Sjkunz 
933*993229b6Sjkunz //! Performs shell-like variable substitution on the string passed into it.
934*993229b6Sjkunz //! Both sources and constants can be substituted. Sources will be replaced
935*993229b6Sjkunz //! with their path and constants with their integer value. The syntax allows
936*993229b6Sjkunz //! for some simple formatting for constants.
937*993229b6Sjkunz //!
938*993229b6Sjkunz //! The syntax is mostly standard. A substitution begins with a dollar-sign
939*993229b6Sjkunz //! and is followed by the source or constant name in parentheses. For instance,
940*993229b6Sjkunz //! "$(mysource)" or "$(myconst)". The parentheses are always required.
941*993229b6Sjkunz //!
942*993229b6Sjkunz //! Constant names can be prefixed by a single formatting character followed
943*993229b6Sjkunz //! by a colon. The only formatting characters currently supported are 'd' for
944*993229b6Sjkunz //! decimal and 'x' for hex. For example, "$(x:myconst)" will be replaced with
945*993229b6Sjkunz //! the value of the constant named "myconst" formatted as hexadecimal. The
946*993229b6Sjkunz //! default is decimal, so the 'd' formatting character isn't really ever
947*993229b6Sjkunz //! needed.
948*993229b6Sjkunz //!
949*993229b6Sjkunz //! \param message The string to perform substitution on.
950*993229b6Sjkunz //! \return Returns a newly allocated std::string object that has all
951*993229b6Sjkunz //!		substitutions replaced with the associated value. The caller is
952*993229b6Sjkunz //!		responsible for freeing the string object using the delete operator.
substituteVariables(const std::string * message)953*993229b6Sjkunz std::string * ConversionController::substituteVariables(const std::string * message)
954*993229b6Sjkunz {
955*993229b6Sjkunz 	string * result = new string();
956*993229b6Sjkunz 	int i;
957*993229b6Sjkunz 	int state = 0;
958*993229b6Sjkunz 	string name;
959*993229b6Sjkunz 
960*993229b6Sjkunz 	for (i=0; i < message->size(); ++i)
961*993229b6Sjkunz 	{
962*993229b6Sjkunz 		char c = (*message)[i];
963*993229b6Sjkunz 		switch (state)
964*993229b6Sjkunz 		{
965*993229b6Sjkunz 			case 0:
966*993229b6Sjkunz 				if (c == '$')
967*993229b6Sjkunz 				{
968*993229b6Sjkunz 					state = 1;
969*993229b6Sjkunz 				}
970*993229b6Sjkunz 				else
971*993229b6Sjkunz 				{
972*993229b6Sjkunz 					(*result) += c;
973*993229b6Sjkunz 				}
974*993229b6Sjkunz 				break;
975*993229b6Sjkunz 
976*993229b6Sjkunz 			case 1:
977*993229b6Sjkunz 				if (c == '(')
978*993229b6Sjkunz 				{
979*993229b6Sjkunz 					state = 2;
980*993229b6Sjkunz 				}
981*993229b6Sjkunz 				else
982*993229b6Sjkunz 				{
983*993229b6Sjkunz 					// Wasn't a variable substitution, so revert to initial state after
984*993229b6Sjkunz 					// inserting the original characters.
985*993229b6Sjkunz 					(*result) += '$';
986*993229b6Sjkunz 					(*result) += c;
987*993229b6Sjkunz 					state = 0;
988*993229b6Sjkunz 				}
989*993229b6Sjkunz 				break;
990*993229b6Sjkunz 
991*993229b6Sjkunz 			case 2:
992*993229b6Sjkunz 				if (c == ')')
993*993229b6Sjkunz 				{
994*993229b6Sjkunz 					// Try the name as a source name first.
995*993229b6Sjkunz 					if (m_sources.find(name) != m_sources.end())
996*993229b6Sjkunz 					{
997*993229b6Sjkunz 						(*result) += m_sources[name]->getPath();
998*993229b6Sjkunz 					}
999*993229b6Sjkunz 					// Otherwise try it as a variable.
1000*993229b6Sjkunz 					else
1001*993229b6Sjkunz 					{
1002*993229b6Sjkunz 						// Select format.
1003*993229b6Sjkunz 						const char * fmt = "%d";
1004*993229b6Sjkunz 						if (name[1] == ':' && (name[0] == 'd' || name[0] == 'x'))
1005*993229b6Sjkunz 						{
1006*993229b6Sjkunz 							if (name[0] == 'x')
1007*993229b6Sjkunz 							{
1008*993229b6Sjkunz 								fmt = "0x%x";
1009*993229b6Sjkunz 							}
1010*993229b6Sjkunz 
1011*993229b6Sjkunz 							// Delete the format characters.
1012*993229b6Sjkunz 							name.erase(0, 2);
1013*993229b6Sjkunz 						}
1014*993229b6Sjkunz 
1015*993229b6Sjkunz 						// Now insert the formatted variable if it exists.
1016*993229b6Sjkunz 						if (m_context.isVariableDefined(name))
1017*993229b6Sjkunz 						{
1018*993229b6Sjkunz 							(*result) += format_string(fmt, m_context.getVariableValue(name));
1019*993229b6Sjkunz 						}
1020*993229b6Sjkunz 					}
1021*993229b6Sjkunz 
1022*993229b6Sjkunz 					// Switch back to initial state and clear name.
1023*993229b6Sjkunz 					state = 0;
1024*993229b6Sjkunz 					name.clear();
1025*993229b6Sjkunz 				}
1026*993229b6Sjkunz 				else
1027*993229b6Sjkunz 				{
1028*993229b6Sjkunz 					// Just keep building up the variable name.
1029*993229b6Sjkunz 					name += c;
1030*993229b6Sjkunz 				}
1031*993229b6Sjkunz 				break;
1032*993229b6Sjkunz 		}
1033*993229b6Sjkunz 	}
1034*993229b6Sjkunz 
1035*993229b6Sjkunz 	return result;
1036*993229b6Sjkunz }
1037*993229b6Sjkunz 
1038*993229b6Sjkunz //!
1039*993229b6Sjkunz //! \param generator The generator to use.
generateOutput(BootImageGenerator * generator)1040*993229b6Sjkunz BootImage * ConversionController::generateOutput(BootImageGenerator * generator)
1041*993229b6Sjkunz {
1042*993229b6Sjkunz 	// set the generator's option context
1043*993229b6Sjkunz 	generator->setOptionContext(this);
1044*993229b6Sjkunz 
1045*993229b6Sjkunz 	// add output sections to the generator in sequence
1046*993229b6Sjkunz 	section_vector_t::iterator it = m_outputSections.begin();
1047*993229b6Sjkunz 	for (; it != m_outputSections.end(); ++it)
1048*993229b6Sjkunz 	{
1049*993229b6Sjkunz 		generator->addOutputSection(*it);
1050*993229b6Sjkunz 	}
1051*993229b6Sjkunz 
1052*993229b6Sjkunz 	// and produce the output
1053*993229b6Sjkunz 	BootImage * image = generator->generate();
1054*993229b6Sjkunz //	Log::log("boot image = %p\n", image);
1055*993229b6Sjkunz 	return image;
1056*993229b6Sjkunz }
1057*993229b6Sjkunz 
1058*993229b6Sjkunz //! Takes an AST node that is one of the following subclasses and creates the corresponding
1059*993229b6Sjkunz //! type of DataSource object from it.
1060*993229b6Sjkunz //! - StringConstASTNode
1061*993229b6Sjkunz //! - ExprASTNode
1062*993229b6Sjkunz //! - SourceASTNode
1063*993229b6Sjkunz //! - SectionASTNode
1064*993229b6Sjkunz //! - SectionMatchListASTNode
1065*993229b6Sjkunz //! - BlobConstASTNode
1066*993229b6Sjkunz //! - IVTConstASTNode
1067*993229b6Sjkunz //!
1068*993229b6Sjkunz //! \exception elftosb::semantic_error Thrown if a semantic problem is found with
1069*993229b6Sjkunz //!		the data node.
1070*993229b6Sjkunz //! \exception std::runtime_error Thrown if an error occurs that shouldn't be possible
1071*993229b6Sjkunz //!		based on the grammar.
createSourceFromNode(ASTNode * dataNode)1072*993229b6Sjkunz DataSource * ConversionController::createSourceFromNode(ASTNode * dataNode)
1073*993229b6Sjkunz {
1074*993229b6Sjkunz 	assert(dataNode);
1075*993229b6Sjkunz 
1076*993229b6Sjkunz 	DataSource * source = NULL;
1077*993229b6Sjkunz 	StringConstASTNode * stringNode;
1078*993229b6Sjkunz 	BlobConstASTNode * blobNode;
1079*993229b6Sjkunz 	ExprASTNode * exprNode;
1080*993229b6Sjkunz 	SourceASTNode * sourceNode;
1081*993229b6Sjkunz 	SectionASTNode * sectionNode;
1082*993229b6Sjkunz 	SectionMatchListASTNode * matchListNode;
1083*993229b6Sjkunz     IVTConstASTNode * ivtNode;
1084*993229b6Sjkunz 
1085*993229b6Sjkunz 	if (stringNode = dynamic_cast<StringConstASTNode*>(dataNode))
1086*993229b6Sjkunz 	{
1087*993229b6Sjkunz 		// create a data source with the string contents
1088*993229b6Sjkunz 		std::string * stringData = stringNode->getString();
1089*993229b6Sjkunz 		const uint8_t * stringContents = reinterpret_cast<const uint8_t *>(stringData->c_str());
1090*993229b6Sjkunz 		source = new UnmappedDataSource(stringContents, static_cast<unsigned>(stringData->size()));
1091*993229b6Sjkunz 	}
1092*993229b6Sjkunz 	else if (blobNode = dynamic_cast<BlobConstASTNode*>(dataNode))
1093*993229b6Sjkunz 	{
1094*993229b6Sjkunz 		// create a data source with the raw binary data
1095*993229b6Sjkunz 		Blob * blob = blobNode->getBlob();
1096*993229b6Sjkunz 		source = new UnmappedDataSource(blob->getData(), blob->getLength());
1097*993229b6Sjkunz 	}
1098*993229b6Sjkunz 	else if (exprNode = dynamic_cast<ExprASTNode*>(dataNode))
1099*993229b6Sjkunz 	{
1100*993229b6Sjkunz 		// reduce the expression first
1101*993229b6Sjkunz 		exprNode = exprNode->reduce(m_context);
1102*993229b6Sjkunz 		IntConstExprASTNode * intNode = dynamic_cast<IntConstExprASTNode*>(exprNode);
1103*993229b6Sjkunz 		if (!intNode)
1104*993229b6Sjkunz 		{
1105*993229b6Sjkunz 			throw semantic_error("load pattern expression did not evaluate to an integer");
1106*993229b6Sjkunz 		}
1107*993229b6Sjkunz 
1108*993229b6Sjkunz 		SizedIntegerValue intValue(intNode->getValue(), intNode->getSize());
1109*993229b6Sjkunz 		source = new PatternSource(intValue);
1110*993229b6Sjkunz 	}
1111*993229b6Sjkunz 	else if (sourceNode = dynamic_cast<SourceASTNode*>(dataNode))
1112*993229b6Sjkunz 	{
1113*993229b6Sjkunz 		// load the entire source contents
1114*993229b6Sjkunz 		SourceFile * sourceFile = getSourceFromName(sourceNode->getSourceName(), sourceNode->getFirstLine());
1115*993229b6Sjkunz 		source = sourceFile->createDataSource();
1116*993229b6Sjkunz 	}
1117*993229b6Sjkunz 	else if (sectionNode = dynamic_cast<SectionASTNode*>(dataNode))
1118*993229b6Sjkunz 	{
1119*993229b6Sjkunz 		// load some subset of the source
1120*993229b6Sjkunz 		SourceFile * sourceFile = getSourceFromName(sectionNode->getSourceName(), sectionNode->getFirstLine());
1121*993229b6Sjkunz 		if (!sourceFile->supportsNamedSections())
1122*993229b6Sjkunz 		{
1123*993229b6Sjkunz 			throw semantic_error(format_string("line %d: source does not support sections", sectionNode->getFirstLine()));
1124*993229b6Sjkunz 		}
1125*993229b6Sjkunz 
1126*993229b6Sjkunz 		// create data source from the section name
1127*993229b6Sjkunz 		std::string * sectionName = sectionNode->getSectionName();
1128*993229b6Sjkunz 		GlobMatcher globber(*sectionName);
1129*993229b6Sjkunz 		source = sourceFile->createDataSource(globber);
1130*993229b6Sjkunz 		if (!source)
1131*993229b6Sjkunz 		{
1132*993229b6Sjkunz 			throw semantic_error(format_string("line %d: no sections match the pattern", sectionNode->getFirstLine()));
1133*993229b6Sjkunz 		}
1134*993229b6Sjkunz 	}
1135*993229b6Sjkunz 	else if (matchListNode = dynamic_cast<SectionMatchListASTNode*>(dataNode))
1136*993229b6Sjkunz 	{
1137*993229b6Sjkunz 		SourceFile * sourceFile = getSourceFromName(matchListNode->getSourceName(), matchListNode->getFirstLine());
1138*993229b6Sjkunz 		if (!sourceFile->supportsNamedSections())
1139*993229b6Sjkunz 		{
1140*993229b6Sjkunz 			throw semantic_error(format_string("line %d: source type does not support sections", matchListNode->getFirstLine()));
1141*993229b6Sjkunz 		}
1142*993229b6Sjkunz 
1143*993229b6Sjkunz 		// create string matcher
1144*993229b6Sjkunz 		ExcludesListMatcher matcher;
1145*993229b6Sjkunz 
1146*993229b6Sjkunz 		// add each pattern to the matcher
1147*993229b6Sjkunz 		ListASTNode * matchList = matchListNode->getSections();
1148*993229b6Sjkunz 		ListASTNode::iterator it = matchList->begin();
1149*993229b6Sjkunz 		for (; it != matchList->end(); ++it)
1150*993229b6Sjkunz 		{
1151*993229b6Sjkunz 			ASTNode * node = *it;
1152*993229b6Sjkunz 			sectionNode = dynamic_cast<SectionASTNode*>(node);
1153*993229b6Sjkunz 			if (!sectionNode)
1154*993229b6Sjkunz 			{
1155*993229b6Sjkunz 				throw std::runtime_error(format_string("line %d: unexpected node type in section pattern list", (*it)->getFirstLine()));
1156*993229b6Sjkunz 			}
1157*993229b6Sjkunz 			bool isInclude = sectionNode->getAction() == SectionASTNode::kInclude;
1158*993229b6Sjkunz 			matcher.addPattern(isInclude, *(sectionNode->getSectionName()));
1159*993229b6Sjkunz 		}
1160*993229b6Sjkunz 
1161*993229b6Sjkunz 		// create data source from the section match list
1162*993229b6Sjkunz 		source = sourceFile->createDataSource(matcher);
1163*993229b6Sjkunz 		if (!source)
1164*993229b6Sjkunz 		{
1165*993229b6Sjkunz 			throw semantic_error(format_string("line %d: no sections match the section pattern list", matchListNode->getFirstLine()));
1166*993229b6Sjkunz 		}
1167*993229b6Sjkunz 	}
1168*993229b6Sjkunz     else if (ivtNode = dynamic_cast<IVTConstASTNode*>(dataNode))
1169*993229b6Sjkunz     {
1170*993229b6Sjkunz         source = createIVTDataSource(ivtNode);
1171*993229b6Sjkunz     }
1172*993229b6Sjkunz 	else
1173*993229b6Sjkunz 	{
1174*993229b6Sjkunz 		throw semantic_error(format_string("line %d: unexpected load data node type", dataNode->getFirstLine()));
1175*993229b6Sjkunz 	}
1176*993229b6Sjkunz 
1177*993229b6Sjkunz 	return source;
1178*993229b6Sjkunz }
1179*993229b6Sjkunz 
createIVTDataSource(IVTConstASTNode * ivtNode)1180*993229b6Sjkunz DataSource * ConversionController::createIVTDataSource(IVTConstASTNode * ivtNode)
1181*993229b6Sjkunz {
1182*993229b6Sjkunz     IVTDataSource * source = new IVTDataSource;
1183*993229b6Sjkunz 
1184*993229b6Sjkunz     // Iterate over the assignment statements in the IVT definition.
1185*993229b6Sjkunz     ListASTNode * fieldList = ivtNode->getFieldAssignments();
1186*993229b6Sjkunz 
1187*993229b6Sjkunz     if (fieldList)
1188*993229b6Sjkunz     {
1189*993229b6Sjkunz         ListASTNode::iterator it = fieldList->begin();
1190*993229b6Sjkunz         for (; it != fieldList->end(); ++it)
1191*993229b6Sjkunz         {
1192*993229b6Sjkunz             AssignmentASTNode * assignmentNode = dynamic_cast<AssignmentASTNode*>(*it);
1193*993229b6Sjkunz             if (!assignmentNode)
1194*993229b6Sjkunz             {
1195*993229b6Sjkunz                 throw std::runtime_error(format_string("line %d: unexpected node type in IVT definition", (*it)->getFirstLine()));
1196*993229b6Sjkunz             }
1197*993229b6Sjkunz 
1198*993229b6Sjkunz             // Get the IVT field name.
1199*993229b6Sjkunz             std::string * fieldName = assignmentNode->getIdent();
1200*993229b6Sjkunz 
1201*993229b6Sjkunz             // Reduce the field expression and get the integer result.
1202*993229b6Sjkunz             ASTNode * valueNode = assignmentNode->getValue();
1203*993229b6Sjkunz             ExprASTNode * valueExpr = dynamic_cast<ExprASTNode*>(valueNode);
1204*993229b6Sjkunz             if (!valueExpr)
1205*993229b6Sjkunz             {
1206*993229b6Sjkunz                 throw semantic_error("IVT field must have a valid expression");
1207*993229b6Sjkunz             }
1208*993229b6Sjkunz             IntConstExprASTNode * valueIntExpr = dynamic_cast<IntConstExprASTNode*>(valueExpr->reduce(m_context));
1209*993229b6Sjkunz             if (!valueIntExpr)
1210*993229b6Sjkunz             {
1211*993229b6Sjkunz                 throw semantic_error(format_string("line %d: IVT field '%s' does not evaluate to an integer", valueNode->getFirstLine(), fieldName->c_str()));
1212*993229b6Sjkunz             }
1213*993229b6Sjkunz             uint32_t value = static_cast<uint32_t>(valueIntExpr->getValue());
1214*993229b6Sjkunz 
1215*993229b6Sjkunz             // Set the field in the IVT data source.
1216*993229b6Sjkunz             if (!source->setFieldByName(*fieldName, value))
1217*993229b6Sjkunz             {
1218*993229b6Sjkunz                 throw semantic_error(format_string("line %d: unknown IVT field '%s'", assignmentNode->getFirstLine(), fieldName->c_str()));
1219*993229b6Sjkunz             }
1220*993229b6Sjkunz         }
1221*993229b6Sjkunz     }
1222*993229b6Sjkunz 
1223*993229b6Sjkunz     return source;
1224*993229b6Sjkunz }
1225*993229b6Sjkunz 
1226*993229b6Sjkunz //! Takes an AST node subclass and returns an appropriate DataTarget object that contains
1227*993229b6Sjkunz //! the same information. Supported AST node types are:
1228*993229b6Sjkunz //! - SymbolASTNode
1229*993229b6Sjkunz //! - NaturalLocationASTNode
1230*993229b6Sjkunz //! - AddressRangeASTNode
1231*993229b6Sjkunz //!
1232*993229b6Sjkunz //! \exception elftosb::semantic_error Thrown if a semantic problem is found with
1233*993229b6Sjkunz //!		the target node.
createTargetFromNode(ASTNode * targetNode)1234*993229b6Sjkunz DataTarget * ConversionController::createTargetFromNode(ASTNode * targetNode)
1235*993229b6Sjkunz {
1236*993229b6Sjkunz 	assert(targetNode);
1237*993229b6Sjkunz 
1238*993229b6Sjkunz 	DataTarget * target = NULL;
1239*993229b6Sjkunz 	SymbolASTNode * symbolNode;
1240*993229b6Sjkunz 	NaturalLocationASTNode * naturalNode;
1241*993229b6Sjkunz 	AddressRangeASTNode * addressNode;
1242*993229b6Sjkunz 
1243*993229b6Sjkunz 	if (symbolNode = dynamic_cast<SymbolASTNode*>(targetNode))
1244*993229b6Sjkunz 	{
1245*993229b6Sjkunz 		SourceFile * sourceFile = getSourceFromName(symbolNode->getSource(), symbolNode->getFirstLine());
1246*993229b6Sjkunz 		std::string * symbolName = symbolNode->getSymbolName();
1247*993229b6Sjkunz 
1248*993229b6Sjkunz 		// symbol name is optional
1249*993229b6Sjkunz 		if (symbolName)
1250*993229b6Sjkunz 		{
1251*993229b6Sjkunz 			if (!sourceFile->supportsNamedSymbols())
1252*993229b6Sjkunz 			{
1253*993229b6Sjkunz 				throw std::runtime_error(format_string("line %d: source does not support symbols", symbolNode->getFirstLine()));
1254*993229b6Sjkunz 			}
1255*993229b6Sjkunz 
1256*993229b6Sjkunz 			target = sourceFile->createDataTargetForSymbol(*symbolName);
1257*993229b6Sjkunz 			if (!target)
1258*993229b6Sjkunz 			{
1259*993229b6Sjkunz 				throw std::runtime_error(format_string("line %d: source does not have a symbol with that name", symbolNode->getFirstLine()));
1260*993229b6Sjkunz 			}
1261*993229b6Sjkunz 		}
1262*993229b6Sjkunz 		else
1263*993229b6Sjkunz 		{
1264*993229b6Sjkunz 			// no symbol name was specified so use entry point
1265*993229b6Sjkunz 			target = sourceFile->createDataTargetForEntryPoint();
1266*993229b6Sjkunz 			if (!target)
1267*993229b6Sjkunz 			{
1268*993229b6Sjkunz 				throw std::runtime_error(format_string("line %d: source does not have an entry point", symbolNode->getFirstLine()));
1269*993229b6Sjkunz 			}
1270*993229b6Sjkunz 		}
1271*993229b6Sjkunz 	}
1272*993229b6Sjkunz 	else if (naturalNode = dynamic_cast<NaturalLocationASTNode*>(targetNode))
1273*993229b6Sjkunz 	{
1274*993229b6Sjkunz 		// the target is the source's natural location
1275*993229b6Sjkunz 		target = new NaturalDataTarget();
1276*993229b6Sjkunz 	}
1277*993229b6Sjkunz 	else if (addressNode = dynamic_cast<AddressRangeASTNode*>(targetNode))
1278*993229b6Sjkunz 	{
1279*993229b6Sjkunz 		// evaluate begin address
1280*993229b6Sjkunz 		ExprASTNode * beginExpr = dynamic_cast<ExprASTNode*>(addressNode->getBegin());
1281*993229b6Sjkunz 		if (!beginExpr)
1282*993229b6Sjkunz 		{
1283*993229b6Sjkunz 			throw semantic_error("address range must always have a beginning expression");
1284*993229b6Sjkunz 		}
1285*993229b6Sjkunz 		IntConstExprASTNode * beginIntExpr = dynamic_cast<IntConstExprASTNode*>(beginExpr->reduce(m_context));
1286*993229b6Sjkunz 		if (!beginIntExpr)
1287*993229b6Sjkunz 		{
1288*993229b6Sjkunz 			throw semantic_error("address range begin did not evaluate to an integer");
1289*993229b6Sjkunz 		}
1290*993229b6Sjkunz 		uint32_t beginAddress = static_cast<uint32_t>(beginIntExpr->getValue());
1291*993229b6Sjkunz 
1292*993229b6Sjkunz 		// evaluate end address
1293*993229b6Sjkunz 		ExprASTNode * endExpr = dynamic_cast<ExprASTNode*>(addressNode->getEnd());
1294*993229b6Sjkunz 		uint32_t endAddress = 0;
1295*993229b6Sjkunz 		bool hasEndAddress = false;
1296*993229b6Sjkunz 		if (endExpr)
1297*993229b6Sjkunz 		{
1298*993229b6Sjkunz 			IntConstExprASTNode * endIntExpr = dynamic_cast<IntConstExprASTNode*>(endExpr->reduce(m_context));
1299*993229b6Sjkunz 			if (!endIntExpr)
1300*993229b6Sjkunz 			{
1301*993229b6Sjkunz 				throw semantic_error("address range end did not evaluate to an integer");
1302*993229b6Sjkunz 			}
1303*993229b6Sjkunz 			endAddress = static_cast<uint32_t>(endIntExpr->getValue());
1304*993229b6Sjkunz 			hasEndAddress = true;
1305*993229b6Sjkunz 		}
1306*993229b6Sjkunz 
1307*993229b6Sjkunz 		// create target
1308*993229b6Sjkunz 		if (hasEndAddress)
1309*993229b6Sjkunz 		{
1310*993229b6Sjkunz 			target = new ConstantDataTarget(beginAddress, endAddress);
1311*993229b6Sjkunz 		}
1312*993229b6Sjkunz 		else
1313*993229b6Sjkunz 		{
1314*993229b6Sjkunz 			target = new ConstantDataTarget(beginAddress);
1315*993229b6Sjkunz 		}
1316*993229b6Sjkunz 	}
1317*993229b6Sjkunz 	else
1318*993229b6Sjkunz 	{
1319*993229b6Sjkunz 		throw semantic_error("unexpected load target node type");
1320*993229b6Sjkunz 	}
1321*993229b6Sjkunz 
1322*993229b6Sjkunz 	return target;
1323*993229b6Sjkunz }
1324*993229b6Sjkunz 
1325*993229b6Sjkunz //! \param sourceName Pointer to string containing the name of the source to look up.
1326*993229b6Sjkunz //!		May be NULL, in which case the default source is used.
1327*993229b6Sjkunz //! \param line The line number on which the source name was located.
1328*993229b6Sjkunz //!
1329*993229b6Sjkunz //! \result A source file object that was previously created in the processSources()
1330*993229b6Sjkunz //!		stage.
1331*993229b6Sjkunz //!
1332*993229b6Sjkunz //! \exception std::runtime_error Thrown if the source name is invalid, or if it
1333*993229b6Sjkunz //!		was NULL and there is no default source (i.e., we're not inside a from
1334*993229b6Sjkunz //!		statement).
getSourceFromName(std::string * sourceName,int line)1335*993229b6Sjkunz SourceFile * ConversionController::getSourceFromName(std::string * sourceName, int line)
1336*993229b6Sjkunz {
1337*993229b6Sjkunz 	SourceFile * sourceFile = NULL;
1338*993229b6Sjkunz 	if (sourceName)
1339*993229b6Sjkunz 	{
1340*993229b6Sjkunz 		// look up source in map
1341*993229b6Sjkunz 		source_map_t::iterator it = m_sources.find(*sourceName);
1342*993229b6Sjkunz 		if (it == m_sources.end())
1343*993229b6Sjkunz 		{
1344*993229b6Sjkunz 			source_name_vector_t::const_iterator findIt = std::find<source_name_vector_t::const_iterator, std::string>(m_failedSources.begin(), m_failedSources.end(), *sourceName);
1345*993229b6Sjkunz 			if (findIt != m_failedSources.end())
1346*993229b6Sjkunz 			{
1347*993229b6Sjkunz 				throw semantic_error(format_string("line %d: error opening source '%s'", line, sourceName->c_str()));
1348*993229b6Sjkunz 			}
1349*993229b6Sjkunz 			else
1350*993229b6Sjkunz 			{
1351*993229b6Sjkunz 				throw semantic_error(format_string("line %d: invalid source name '%s'", line, sourceName->c_str()));
1352*993229b6Sjkunz 			}
1353*993229b6Sjkunz 		}
1354*993229b6Sjkunz 		sourceFile = it->second;
1355*993229b6Sjkunz 	}
1356*993229b6Sjkunz 	else
1357*993229b6Sjkunz 	{
1358*993229b6Sjkunz 		// no name provided - use default source
1359*993229b6Sjkunz 		sourceFile = m_defaultSource;
1360*993229b6Sjkunz 		if (!sourceFile)
1361*993229b6Sjkunz 		{
1362*993229b6Sjkunz 			throw semantic_error(format_string("line %d: source required but no default source is available", line));
1363*993229b6Sjkunz 		}
1364*993229b6Sjkunz 	}
1365*993229b6Sjkunz 
1366*993229b6Sjkunz 	// open the file if it hasn't already been
1367*993229b6Sjkunz 	if (!sourceFile->isOpen())
1368*993229b6Sjkunz 	{
1369*993229b6Sjkunz 		sourceFile->open();
1370*993229b6Sjkunz 	}
1371*993229b6Sjkunz 	return sourceFile;
1372*993229b6Sjkunz }
1373*993229b6Sjkunz 
1374*993229b6Sjkunz //! Exercises the lexer by printing out the value of every token produced by the
1375*993229b6Sjkunz //! lexer. It is assumed that the lexer object has already be configured to read
1376*993229b6Sjkunz //! from some input file. The method will return when the lexer has exhausted all
1377*993229b6Sjkunz //! tokens, or an error occurs.
testLexer(ElftosbLexer & lexer)1378*993229b6Sjkunz void ConversionController::testLexer(ElftosbLexer & lexer)
1379*993229b6Sjkunz {
1380*993229b6Sjkunz 	// test lexer
1381*993229b6Sjkunz 	while (1)
1382*993229b6Sjkunz 	{
1383*993229b6Sjkunz 		YYSTYPE value;
1384*993229b6Sjkunz 		int lexresult = lexer.yylex();
1385*993229b6Sjkunz 		if (lexresult == 0)
1386*993229b6Sjkunz 			break;
1387*993229b6Sjkunz 		lexer.getSymbolValue(&value);
1388*993229b6Sjkunz 		Log::log("%d -> int:%d, ast:%p", lexresult, value.m_int, value.m_str, value.m_ast);
1389*993229b6Sjkunz 		if (lexresult == TOK_IDENT || lexresult == TOK_SOURCE_NAME || lexresult == TOK_STRING_LITERAL)
1390*993229b6Sjkunz 		{
1391*993229b6Sjkunz 			if (value.m_str)
1392*993229b6Sjkunz 			{
1393*993229b6Sjkunz 				Log::log(", str:%s\n", value.m_str->c_str());
1394*993229b6Sjkunz 			}
1395*993229b6Sjkunz 			else
1396*993229b6Sjkunz 			{
1397*993229b6Sjkunz 				Log::log("str:NULL\n");
1398*993229b6Sjkunz 			}
1399*993229b6Sjkunz 		}
1400*993229b6Sjkunz 		else
1401*993229b6Sjkunz 		{
1402*993229b6Sjkunz 			Log::log("\n");
1403*993229b6Sjkunz 		}
1404*993229b6Sjkunz 	}
1405*993229b6Sjkunz }
1406*993229b6Sjkunz 
1407*993229b6Sjkunz //! Prints out the value of an integer constant expression AST node. Also prints
1408*993229b6Sjkunz //! the name of the identifier associated with that node, as well as the integer
1409*993229b6Sjkunz //! size.
printIntConstExpr(const std::string & ident,IntConstExprASTNode * expr)1410*993229b6Sjkunz void ConversionController::printIntConstExpr(const std::string & ident, IntConstExprASTNode * expr)
1411*993229b6Sjkunz {
1412*993229b6Sjkunz 	// print constant value
1413*993229b6Sjkunz 	char sizeChar;
1414*993229b6Sjkunz 	switch (expr->getSize())
1415*993229b6Sjkunz 	{
1416*993229b6Sjkunz 		case kWordSize:
1417*993229b6Sjkunz 			sizeChar = 'w';
1418*993229b6Sjkunz 			break;
1419*993229b6Sjkunz 		case kHalfWordSize:
1420*993229b6Sjkunz 			sizeChar = 'h';
1421*993229b6Sjkunz 			break;
1422*993229b6Sjkunz 		case kByteSize:
1423*993229b6Sjkunz 			sizeChar = 'b';
1424*993229b6Sjkunz 			break;
1425*993229b6Sjkunz 	}
1426*993229b6Sjkunz 	Log::log("%s => %d:%c\n", ident.c_str(), expr->getValue(), sizeChar);
1427*993229b6Sjkunz }
1428*993229b6Sjkunz 
1429