xref: /aoo41x/main/idlc/source/idlccompile.cxx (revision 24c56ab9)
1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 // MARKER(update_precomp.py): autogen include statement, do not remove
25 #include "precompiled_idlc.hxx"
26 #include <idlc/idlc.hxx>
27 #include <rtl/ustring.hxx>
28 #include <rtl/strbuf.hxx>
29 #include <osl/process.h>
30 #include <osl/diagnose.h>
31 #include <osl/thread.h>
32 #include <osl/file.hxx>
33 
34 #if defined(SAL_W32) || defined(SAL_OS2)
35 #include <io.h>
36 #endif
37 
38 #ifdef  SAL_UNX
39 #include <unistd.h>
40 #if defined(MACOSX) || defined(FREEBSD) || defined(NETBSD)
41 #include <sys/wait.h>
42 #else
43 #include <wait.h>
44 #endif
45 #endif
46 
47 #include <string.h>
48 
49 using namespace ::rtl;
50 using namespace ::osl;
51 
52 extern int yyparse();
53 extern FILE* yyin;
54 extern int yydebug;
55 
56 sal_Int32 lineNumber = 1;
57 
58 
59 static OUString TMP(RTL_CONSTASCII_USTRINGPARAM("TMP"));
60 static OUString TEMP(RTL_CONSTASCII_USTRINGPARAM("TEMP"));
61 static sal_Char tmpFilePattern[512];
62 
isFileUrl(const OString & fileName)63 sal_Bool isFileUrl(const OString& fileName)
64 {
65     if (fileName.indexOf("file://") == 0 )
66         return sal_True;
67     return sal_False;
68 }
69 
convertToAbsoluteSystemPath(const OString & fileName)70 OString convertToAbsoluteSystemPath(const OString& fileName)
71 {
72     OUString uSysFileName;
73     OUString uFileName(fileName.getStr(), fileName.getLength(), osl_getThreadTextEncoding());
74     if ( isFileUrl(fileName) )
75     {
76         if (FileBase::getSystemPathFromFileURL(uFileName, uSysFileName)
77             != FileBase::E_None)
78         {
79             OSL_ASSERT(false);
80         }
81     } else
82     {
83         OUString uWorkingDir, uUrlFileName, uTmp;
84         if (osl_getProcessWorkingDir(&uWorkingDir.pData) != osl_Process_E_None)
85         {
86             OSL_ASSERT(false);
87         }
88         if (FileBase::getFileURLFromSystemPath(uFileName, uTmp)
89             != FileBase::E_None)
90         {
91             OSL_ASSERT(false);
92         }
93         if (FileBase::getAbsoluteFileURL(uWorkingDir, uTmp, uUrlFileName)
94             != FileBase::E_None)
95         {
96             OSL_ASSERT(false);
97         }
98         if (FileBase::getSystemPathFromFileURL(uUrlFileName, uSysFileName)
99             != FileBase::E_None)
100         {
101             OSL_ASSERT(false);
102         }
103     }
104 
105     return OUStringToOString(uSysFileName, osl_getThreadTextEncoding());
106 }
107 
convertToFileUrl(const OString & fileName)108 OString convertToFileUrl(const OString& fileName)
109 {
110     if ( !isFileUrl(fileName) )
111     {
112         OString tmp = convertToAbsoluteSystemPath(fileName);
113         OUString uFileName(tmp.getStr(), tmp.getLength(), osl_getThreadTextEncoding());
114         OUString uUrlFileName;
115         if (FileBase::getFileURLFromSystemPath(uFileName, uUrlFileName)
116             != FileBase::E_None)
117         {
118             OSL_ASSERT(false);
119         }
120         return OUStringToOString(uUrlFileName, osl_getThreadTextEncoding());
121     }
122 
123     return fileName;
124 }
125 
makeTempName(const OString & prefix)126 OString makeTempName(const OString& prefix)
127 {
128     OUString uTmpPath;
129     OString tmpPath;
130 
131     if ( osl_getEnvironment(TMP.pData, &uTmpPath.pData) != osl_Process_E_None )
132     {
133         if ( osl_getEnvironment(TEMP.pData, &uTmpPath.pData) != osl_Process_E_None )
134         {
135 #if defined(SAL_W32)
136             tmpPath = OString("c:\\temp");
137 #else
138             tmpPath = OString("/tmp");
139 #endif
140         }
141     }
142 
143     if ( uTmpPath.getLength() )
144         tmpPath = OUStringToOString(uTmpPath, RTL_TEXTENCODING_UTF8);
145 
146 #if defined(SAL_W32) || defined(SAL_UNX) || defined(SAL_OS2)
147 
148     OSL_ASSERT( sizeof(tmpFilePattern) > ( tmpPath.getLength()
149                                            + RTL_CONSTASCII_LENGTH(
150                                                 PATH_SEPARATOR )
151                                            + prefix.getLength()
152                                            + RTL_CONSTASCII_LENGTH(
153                                                 "XXXXXX") ) );
154 
155     tmpFilePattern[ sizeof(tmpFilePattern)-1 ] = '\0';
156     strncpy(tmpFilePattern, tmpPath.getStr(), sizeof(tmpFilePattern)-1);
157     strncat(tmpFilePattern, PATH_SEPARATOR, sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));
158     strncat(tmpFilePattern, prefix.getStr(), sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));
159     strncat(tmpFilePattern, "XXXXXX", sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));
160 
161 #ifdef SAL_UNX
162     int nDescriptor = mkstemp(tmpFilePattern);
163     if( -1 == nDescriptor )
164     {
165         fprintf( stderr,"idlc: couldn't create temporary file %s\n", tmpFilePattern );
166         exit( 1 );
167     }
168     // the file shall later be reopened by stdio functions
169     close( nDescriptor );
170 #else
171     (void) mktemp(tmpFilePattern);
172 #endif
173 #endif
174 
175     return OString(tmpFilePattern);
176 }
177 
copyFile(const OString * source,const OString & target)178 sal_Bool copyFile(const OString* source, const OString& target)
179 {
180     sal_Bool bRet = sal_True;
181 
182     FILE* pSource = source == 0 ? stdin : fopen(source->getStr(), "rb");
183     if ( !pSource )
184         return sal_False;
185 
186     FILE* pTarget = fopen(target.getStr(), "wb");
187     if ( !pTarget )
188     {
189         fclose(pSource);
190         return sal_False;
191     }
192 
193     size_t totalSize = 512;
194     size_t readSize  = 0;
195     size_t writeSize = 0;
196     char   pBuffer[513];
197 
198     while ( !feof(pSource) )
199     {
200         if ( (readSize = fread(pBuffer, 1, totalSize, pSource)) > 0 && !ferror(pSource) )
201         {
202             if ( (writeSize = fwrite(pBuffer, 1, readSize, pTarget)) != readSize || ferror(pTarget) )
203             {
204                 if (source != 0) {
205                     fclose(pSource);
206                 }
207                 fclose(pTarget);
208                 return sal_False;
209             }
210         }
211     }
212 
213     if (source != 0) {
214         fclose(pSource);
215     }
216     if ( fflush(pTarget) )
217         bRet = sal_False;
218     fclose(pTarget);
219 
220     return bRet;
221 }
222 
compileFile(const OString * pathname)223 sal_Int32 compileFile(const OString * pathname)
224 {
225     // preprocess input file
226     OString tmpFile = makeTempName(OString("idli_"));
227     OString preprocFile = makeTempName(OString("idlf_"));
228 
229     OString fileName;
230     if (pathname == 0) {
231         fileName = "stdin";
232     } else {
233         fileName = *pathname;
234     }
235 
236     if ( !copyFile(pathname, tmpFile) )
237     {
238         fprintf(stderr, "%s: could not copy %s%s to %s\n",
239                 idlc()->getOptions()->getProgramName().getStr(),
240                 pathname == 0 ? "" : "file ", fileName.getStr(),
241                 tmpFile.getStr());
242         exit(99);
243     }
244 
245     idlc()->setFileName(fileName);
246     idlc()->setMainFileName(fileName);
247     idlc()->setRealFileName(tmpFile);
248 
249     ::std::vector< ::rtl::OUString > lCppArgs;
250     lCppArgs.push_back(OUString(RTL_CONSTASCII_USTRINGPARAM("-DIDL")));
251     lCppArgs.push_back(OUString(RTL_CONSTASCII_USTRINGPARAM("-C")));
252     lCppArgs.push_back(OUString(RTL_CONSTASCII_USTRINGPARAM("-zI")));
253     lCppArgs.push_back(OUString(RTL_CONSTASCII_USTRINGPARAM("-I.")));
254 
255     OStringBuffer cppArgs(256);
256     Options* pOptions = idlc()->getOptions();
257 
258     OString filePath;
259     sal_Int32 index = fileName.lastIndexOf(SEPARATOR);
260 
261     if ( index > 0)
262     {
263         filePath = fileName.copy(0, index);
264 
265         if ( filePath.getLength() )
266         {
267             cppArgs.append("-I");
268             cppArgs.append(filePath);
269             lCppArgs.push_back(OStringToOUString(cppArgs.makeStringAndClear().replace('\\', '/'), RTL_TEXTENCODING_UTF8));
270 		}
271 	}
272 
273 	if ( pOptions->isValid("-D") )
274 	{
275         OString dOpt = pOptions->getOption("-D");
276         OString token;
277         sal_Int32 nIndex = 0;
278         do
279         {
280             token = dOpt.getToken( 0, ' ', nIndex );
281             if (token.getLength())
282             {
283                 lCppArgs.push_back(OStringToOUString(token, RTL_TEXTENCODING_UTF8));
284             }
285         } while( nIndex != -1 );
286 	}
287 
288 	if ( pOptions->isValid("-I") )
289 	{
290         OString incOpt = pOptions->getOption("-I");
291         OString token;
292         sal_Int32 nIndex = 0;
293         do
294         {
295             token = incOpt.getToken( 0, ' ', nIndex );
296             if (token.getLength())
297             {
298                 lCppArgs.push_back(OStringToOUString(token, RTL_TEXTENCODING_UTF8));
299             }
300         } while( nIndex != -1 );
301 	}
302 
303     lCppArgs.push_back(OUString(RTL_CONSTASCII_USTRINGPARAM("-o")));
304 
305 	cppArgs.append(preprocFile);
306     lCppArgs.push_back(OStringToOUString(cppArgs.makeStringAndClear(), RTL_TEXTENCODING_UTF8));
307 
308     cppArgs.append(tmpFile);
309     lCppArgs.push_back(OStringToOUString(cppArgs.makeStringAndClear(), RTL_TEXTENCODING_UTF8));
310 
311 	OUString cpp;
312 	OUString startDir;
313 	if (osl_getExecutableFile(&cpp.pData) != osl_Process_E_None) {
314         OSL_ASSERT(false);
315     }
316 
317     sal_Int32 idx= cpp.lastIndexOf(OUString( RTL_CONSTASCII_USTRINGPARAM("idlc")) );
318  	cpp = cpp.copy(0, idx);
319 
320 #if defined(SAL_W32) || defined(SAL_OS2)
321  	cpp += OUString( RTL_CONSTASCII_USTRINGPARAM("ucpp.exe"));
322 #else
323 	cpp += OUString( RTL_CONSTASCII_USTRINGPARAM("ucpp"));
324 #endif
325 
326 	oslProcess		hProcess = NULL;
327 	oslProcessError	procError = osl_Process_E_None;
328 
329     const int nCmdArgs = lCppArgs.size();
330     rtl_uString** pCmdArgs = 0;
331     pCmdArgs = (rtl_uString**)rtl_allocateZeroMemory(nCmdArgs * sizeof(rtl_uString*));
332 
333     ::std::vector< ::rtl::OUString >::iterator iter = lCppArgs.begin();
334     ::std::vector< ::rtl::OUString >::iterator end = lCppArgs.end();
335     int i = 0;
336 	while ( iter != end ) {
337         pCmdArgs[i++] = (*iter).pData;
338         ++iter;
339     }
340 
341 	procError = osl_executeProcess(cpp.pData, pCmdArgs, nCmdArgs, osl_Process_WAIT,
342 								   0, startDir.pData, 0, 0, &hProcess);
343 
344 	oslProcessInfo hInfo;
345 	hInfo.Size = (sal_uInt32)(sizeof(oslProcessInfo));
346 	if (osl_getProcessInfo(hProcess, osl_Process_EXITCODE, &hInfo)
347         != osl_Process_E_None)
348     {
349         OSL_ASSERT(false);
350     }
351 
352 	if ( procError || (hInfo.Code != 0) )
353 	{
354 		if ( procError != osl_Process_E_None )
355 			fprintf(stderr, "%s: starting preprocessor failed\n", pOptions->getProgramName().getStr());
356 		else
357 			fprintf(stderr, "%s: preprocessing %s%s failed\n",
358                     pOptions->getProgramName().getStr(),
359                     pathname == 0 ? "" : "file ", fileName.getStr());
360 
361 		// unlink(tmpFile.getStr());
362 		// unlink(preprocFile.getStr());
363 		// unlink(cmdFileName.getStr());
364 		osl_freeProcessHandle(hProcess);
365         rtl_freeMemory(pCmdArgs);
366 		exit(hInfo.Code ? hInfo.Code : 99);
367 	}
368 	osl_freeProcessHandle(hProcess);
369     rtl_freeMemory(pCmdArgs);
370 
371 	if (unlink(tmpFile.getStr()) != 0)
372 	{
373 		fprintf(stderr, "%s: Could not remove cpp input file %s\n",
374 				 pOptions->getProgramName().getStr(), tmpFile.getStr());
375 		exit(99);
376 	}
377 
378 	if ( pOptions->isValid("-E") )
379 	{
380 		if( unlink( preprocFile.getStr()) != 0)
381 		{
382 			fprintf(stderr, "%s: Could not remove parser input file %s\n",
383 				   	pOptions->getProgramName().getStr(), preprocFile.getStr());
384 			exit(99);
385 		}
386 		exit(0);
387 	}
388 
389 	// parse file
390 	yyin = fopen(preprocFile.getStr(), "r");
391 	if (yyin == NULL)
392 	{
393 		fprintf(stderr, "%s: Could not open cpp output file %s\n",
394 			   	pOptions->getProgramName().getStr(), preprocFile.getStr());
395 		exit(99);
396 	}
397 
398 	//yydebug = 0 no trace information
399 	//yydebug = 1 parser produce trace information
400 	yydebug = 0;
401 
402 	sal_Int32 nErrors = yyparse();
403 	nErrors = idlc()->getErrorCount();
404 
405 	fclose(yyin);
406 	if (unlink(preprocFile.getStr()) != 0)
407 	{
408         fprintf(stderr, "%s: Could not remove parser input file %s\n",
409 			    pOptions->getProgramName().getStr(), preprocFile.getStr());
410 		exit(99);
411 	}
412 
413 	return nErrors;
414 }
415