os/ossrv/genericopenlibs/openenvcore/libc/src/getcwd.cpp
author sl
Tue, 10 Jun 2014 14:32:02 +0200
changeset 1 260cb5ec6c19
permissions -rw-r--r--
Update contrib.
     1 /*
     2 * Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
     3 * All rights reserved.
     4 * This component and the accompanying materials are made available
     5 * under the terms of "Eclipse Public License v1.0"
     6 * which accompanies this distribution, and is available
     7 * at the URL "http://www.eclipse.org/legal/epl-v10.html".
     8 *
     9 * Initial Contributors:
    10 * Nokia Corporation - initial contribution.
    11 *
    12 * Contributors:
    13 *
    14 * Description:
    15 */
    16 /*
    17 * ==============================================================================
    18 *  Name        : getcwd.cpp
    19 *  Part of     : libc library
    20 *  Description : gets current working directory.
    21 *
    22 * ============================================================================
    23 */
    24 
    25 #include "sysif.h"
    26 #include <sys/errno.h> //error codes (ENOMEM, EINVAL)
    27 #include "sysreent.h"
    28 #include <string.h> //strlen
    29 #include <stdlib.h>
    30 
    31 extern "C" {
    32 
    33 /*
    34 Gets the path name of the current working directory.
    35 If a buffer is specified, the path name is placed in that buffer,
    36 and the address of the buffer is returned. 
    37 */
    38 EXPORT_C char* getcwd (char *_buf, size_t _size)
    39 	{
    40 	
    41         if (_buf != 0 && _size == 0)
    42 		{
    43 		errno = EINVAL;
    44 		return NULL;
    45 		}
    46 	
    47 	char * _ourbuf = _buf;	
    48 	if (_buf==0)
    49 		{
    50 		if (_size >= (KMaxTInt/2))
    51 			{
    52 			errno=ENOMEM;
    53 			return _buf;
    54 			}
    55 		//coverity[alloc_fn]
    56 		//coverity[assign]
    57 		_ourbuf = (char *)	malloc(_size);
    58 		if (_ourbuf == 0)
    59 			{
    60 			errno=ENOMEM;
    61 			return _buf;
    62 			}
    63 		}
    64 
    65    //we are dealing with wide characters from here so we need a temporary buffer
    66 	wchar_t tmpbuf[KMaxFullName];
    67 	//coverity[leave_without_push]
    68 	wchar_t *cret = _getcwd_r(&errno, tmpbuf, _size);
    69 
    70 	if (cret)	//we have a path
    71 		{
    72 		//convert it to UTF8
    73 		size_t x = wcstombs(_ourbuf, tmpbuf, _size);	//convert the buffer
    74 		
    75 		//remove the trailing backslash
    76               int cwd_len = strlen(_ourbuf);
    77 		if(_ourbuf[cwd_len - 1] == '\\')
    78 			_ourbuf[cwd_len - 1] = '\0';
    79 		
    80 		return _ourbuf;
    81 		}
    82 
    83 	//deal with the fact we may have allocated our own buffer
    84 	if (_buf != _ourbuf)  //we allocated it.
    85 		{
    86 			free(_ourbuf);
    87        	}
    88        	
    89 	return NULL;
    90 	}
    91 
    92 } // extern "C"