197403Sobrien// Support routines for the -*- C++ -*- dynamic memory management.
2169691Skan// Copyright (C) 1997, 1998, 1999, 2000, 2001, 2004 Free Software Foundation
397403Sobrien//
4132720Skan// This file is part of GCC.
597403Sobrien//
6132720Skan// GCC is free software; you can redistribute it and/or modify
797403Sobrien// it under the terms of the GNU General Public License as published by
897403Sobrien// the Free Software Foundation; either version 2, or (at your option)
997403Sobrien// any later version.
1097403Sobrien//
11132720Skan// GCC is distributed in the hope that it will be useful,
1297403Sobrien// but WITHOUT ANY WARRANTY; without even the implied warranty of
1397403Sobrien// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
1497403Sobrien// GNU General Public License for more details.
1597403Sobrien//
1697403Sobrien// You should have received a copy of the GNU General Public License
17132720Skan// along with GCC; see the file COPYING.  If not, write to
18169691Skan// the Free Software Foundation, 51 Franklin Street, Fifth Floor,
19169691Skan// Boston, MA 02110-1301, USA.
2097403Sobrien//
2197403Sobrien// As a special exception, you may use this file as part of a free software
2297403Sobrien// library without restriction.  Specifically, if other files instantiate
2397403Sobrien// templates or use macros or inline functions from this file, or you compile
2497403Sobrien// this file and link it with other files to produce an executable, this
2597403Sobrien// file does not by itself cause the resulting executable to be covered by
2697403Sobrien// the GNU General Public License.  This exception does not however
2797403Sobrien// invalidate any other reasons why the executable file might be covered by
2897403Sobrien// the GNU General Public License.
2997403Sobrien
30169691Skan#include <bits/c++config.h>
31169691Skan#include <exception_defines.h>
3297403Sobrien#include "new"
3397403Sobrien
3497403Sobrienusing std::new_handler;
3597403Sobrienusing std::bad_alloc;
3697403Sobrien
3797403Sobrienextern "C" void *malloc (std::size_t);
3897403Sobrienextern new_handler __new_handler;
3997403Sobrien
40169691Skan_GLIBCXX_WEAK_DEFINITION void *
4197403Sobrienoperator new (std::size_t sz, const std::nothrow_t&) throw()
4297403Sobrien{
4397403Sobrien  void *p;
4497403Sobrien
4597403Sobrien  /* malloc (0) is unpredictable; avoid it.  */
4697403Sobrien  if (sz == 0)
4797403Sobrien    sz = 1;
4897403Sobrien  p = (void *) malloc (sz);
4997403Sobrien  while (p == 0)
5097403Sobrien    {
5197403Sobrien      new_handler handler = __new_handler;
5297403Sobrien      if (! handler)
5397403Sobrien	return 0;
5497403Sobrien      try
5597403Sobrien	{
5697403Sobrien	  handler ();
5797403Sobrien	}
5897403Sobrien      catch (bad_alloc &)
5997403Sobrien	{
6097403Sobrien	  return 0;
6197403Sobrien	}
6297403Sobrien
6397403Sobrien      p = (void *) malloc (sz);
6497403Sobrien    }
6597403Sobrien
6697403Sobrien  return p;
6797403Sobrien}
68