Slashdot Mirror


Microsoft To Banish Memcpy()

kyriacos notes that Microsoft will be adding memcpy() to its list of function calls banned under its secure development lifecycle. This reader asks, "I was wondering how advanced C/C++ programmers view this move. Do you find this having a negative impact on the flexibility of the language, and do you think it will restrict the creativity of the programmer?"

486 comments

  1. No - there are plenty of safer alternatives by MerlynEmrys67 · · Score: 5, Insightful

    Just like removing printf, scanf, and most other copy/string functions. There are safe versions of memcpy that work just fine and are just as easy to use...
    Lame story (Trying for flamebait here?)

    --
    I have mod points and I am not afraid to use them
    1. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 3, Insightful

      And they aren't even removed, but (by default) a warning is issued when using them. I'd say it's a good move - passing the size of the destination buffer is usually not that complicated.

    2. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 4, Insightful

      safe versions - if you prefer to blindly program away, not worrying about where your objects end up in memory. But - what is "safe"? Is there any replacement for properly testing all I/O from all possible sources?

    3. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      Lame story (Trying for flamebait here?)

      Posted by kdawson on Friday May 15, @11:26AM

    4. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 3, Informative

      Internally to Microsoft, "banned" means that no products can be shipped using these functions. Externally, this is just a recommendation.

    5. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 5, Informative

      I'd say it's a good move - passing the size of the destination buffer is usually not that complicated.

      Are you high? It already takes a size argument. If this were about strcpy(3), then you'd have a point, but I do not think memcpy(3) means what you think it means.

      I'm not saying you can't get yourself into trouble with inappropriate use of memcpy(3), but buffer overruns aren't the go-to threat every time.

      NAME
      memcpy - copy memory area

      SYNOPSIS
      #include <string.h>

      void *memcpy(void *dest, const void *src, size_t n);

      DESCRIPTION
      The memcpy() function copies n bytes from memory area src to memory area dest. The memory
      areas should not overlap. Use memmove(3) if the memory areas do overlap.

    6. Re:No - there are plenty of safer alternatives by Chris+Burke · · Score: 5, Informative

      Just like removing printf, scanf, and most other copy/string functions. There are safe versions of memcpy that work just fine and are just as easy to use...

      There's nothing unsafe about printf (since compilers started doing format type checking), as long as you don't use user input as the format string. To print user input, you use printf("%s", user_input).

      strcpy() is unsafe because you don't know how many bytes you are going to be copying. strncpy() is completely safe as long as you aren't brain dead and set the 'n' to the size of the destination buffer (as opposed to strlen(src) which would be brain dead) and then slap an '\0' into the last index of the dest. sprintf, same deal, just use snprintf and tell it the max bytes it can print.

      So what's unsafe about memcpy()? You explicitly specify the number of bytes to copy. If that number of bytes is greater than the known size of the destination buffer, then you've got a problem that simply adding a second 'size of dest' paramater to the copy won't fix because you already screwed the pooch on figuring that out now didn't you?

      Yes memcpy() doesn't work if src and dest overlap. When that's happening, you typically know about it (you've got some clever in-situ array modification going on) and can use memmove(). memmove(), on the other hand, is equally unsafe if you can't properly specify the number of bytes to copy.

      Bottom line: There's no such thing as a "safe" copy in C when we're assuming the programmer can't figure out the destination buffer size.

      --

      The enemies of Democracy are
    7. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      Hu? How do you make memcpy any safer than it currently is? Two size parameters for source and destination?

      memcpy is not like strcpy.. There *IS* a size parameter where you specify exactly how much is supposed to be copied.

      All of the *safe* c functions I've ever seen are concidered safe precisely because they require you to pass in the size parameter so they can check to make sure they do not overrun the buffer.

      In my view the next reasonable step from a safety perspective is a managed environment or compiler which emits code to explicitly enforce bounds in which case you might as well be writing java.

    8. Re:No - there are plenty of safer alternatives by Bill,+Shooter+of+Bul · · Score: 1

      In the same way that having a seat belt and an air bag in my car, doesn't change my driving habits. Using safer functions, shouldn't change the testing required.

      --
      Well.. maybe. Or Maybe not. But Definitely not sort of.
    9. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 5, Insightful

      It's a psychological thing. Having a separate parameter for the size of the destination buffer forces the programmer to think about what that size is. Too often programmers call memcpy passing the size of the data that needs copying and forget to check that the destination is big enough. And that's why we see so many buffer overflows.

      If you never make this mistake continue to use memcpy. I don't care and neither does Microsoft.

    10. Re:No - there are plenty of safer alternatives by dzfoo · · Score: 0, Offtopic

      Bravo! If I had mod points I'd give you some.

              -dZ.

      --
      Carol vs. Ghost
      ...Can you save Christmas?
    11. Re:No - there are plenty of safer alternatives by marc.andrysco · · Score: 1

      That strncpy probably isn't what you're looking for. From here: "If the array pointed to by s2 is a string that is shorter than n bytes, null bytes are appended to the copy in the array pointed to by s1, until n bytes in all are written." So that function isn't a very good idea if your destination buffer is really large and your source buffer is very small.

      For a safe strcpy, you're probably going to want something like strcpy(dest, src, (dest src ? dest : src)). You can expand that out to a full if statement if inline conditionals give you a headache.

    12. Re:No - there are plenty of safer alternatives by FlyingBishop · · Score: 5, Informative

      That's physically impossible, even given infinite time. Read up on the halting problem.

      However, programming a framework in which we may rule out certain things, for example a process jumping over and altering the OS, is perfectly possible. It just has to be verified through reasoning, rather than testing. The unit testing methodology is really the problem here. You cannot unit test everything.

      Don't get me wrong, testing is a good start, but it's no proof of security, and a proof of security, while very hard, is possible. Kudos to Microsoft.

      And to expand on the GP for those that didn't RTFA, they replaced Memcpy with a memcpy that forced you to state the size of the destination buffer, which is a constant time operation, and a much needed one. So this only forces C coders to make their code a little more clear.

      And when you're being intentionally unclear to the computer in addition to the reader, your code has no place in a secure production setting.

    13. Re:No - there are plenty of safer alternatives by NetherNihilist · · Score: 1

      If you're a competent programmer then nothing is unsafe, but obviously there are a lot of stupid programmers out there who make fundamental mistakes fucking with memory when they don't understand what they're doing. What Microsoft is trying to do here is to eliminate a low hanging fruit of software security that has led to hundreds if not thousands of buffer overflow conditions and associated vulnerabilities/exploits. This is a smart thing to do and has been mentioned elsewhere should have been done a LONG time ago. Also, this is just to be compliant with Microsoft's SDLC. It's not like the function is being removed from the C library. A secure development standard should not include functions that can potentially be unsafe, even if they only are 1/100 or 1/1000 times. Even the best programmers make mistakes.

    14. Re:No - there are plenty of safer alternatives by Timmmm · · Score: 1

      You're interpreting 'unsafe' to mean 'possible to exploit/crash'. I think the parent was taking it to mean 'likely to lead to exploitable/crashable code'. You can hardly argue about that. Just look at the number of sprintf/strcpy security vulnerabilities compared to std::string-caused vulnerabilities.

      When writing modern C++ there are very few situations where you need to use memcpy. Still there are some, and I don't think they should get rid of it entirely.

    15. Re:No - there are plenty of safer alternatives by Chirs · · Score: 1

      But that's not a correctness argument, it's a performance argument.

    16. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      I don't think GP was that high...

      memcpy's size argument is for the amount of data to be copied, not for the destination buffer size. Sure, for some cases, these will be the same, but not always.

      memcpy_s's buffer size argument should be used for the actual size of the destination buffer. It shouldn't be variable based on user input / program flow, and can likely be determined at compile time.

      Granted, this doesn't provide anything that the programmer couldn't do with memcpy and some extra code, and it certainly could still be misused. The idea is that it guides the programmer to the safe, correct solution.

    17. Re:No - there are plenty of safer alternatives by Creepy · · Score: 1

      memcpy doesn't verify the size of the receiving buffer is large enough for the copy, so it is possible to overrun the buffer. The returned value is a void*, so checking the buffer would probably need to be done at runtime unless it's explicitly cast at compile time (and the compiler is smart enough to check for that - in C++ you hint with dynamic_cast or static_cast, but how you do it in C I believe depends on compiler).

      Basically, this is a tradeoff of speed vs security. C/C++ usually took speed over security because that was more important when the languages were created. Modern languages generally prefer security over speed because processing power is much greater than it was when C/C++ was invented.

      And how is this any different than MS deprecating other potential memory leak functions like string functions e.g. strcpy for strcpy_s) last year (or is it two years ago now... they were added before the old ones were deprecated I think)?

      I seem to recall the next version of C++ is supposed to add some security, some official threading and built-in garbage collection (of course, some of those features have been planned and dropped in the past, so it could be abandoned again), so you could say C++ is moving toward being more like Java anyway :D

    18. Re:No - there are plenty of safer alternatives by nschubach · · Score: 1

      In the same way that having a seat belt and an air bag in my car, doesn't change my driving habits. Using safer functions, shouldn't change the testing required.

      Drivers are going to try to drive safer with a steel spike in their face instead of a friendly pillow. If people assume that the safety measures in their car will prevent them from being killed, they'd likely accept an accident instead of trying to avoid it. I'm sure someone smarter in psychology and human behavior could argue that better than I just did.

      --
      Every time I start to have faith in humanity, I ruin it by driving to work between 7 and 8 am.
    19. Re:No - there are plenty of safer alternatives by nschubach · · Score: 1

      I should add... I mainly posted that to show that the driving analogy you posted might not be the best one for this situation.

      --
      Every time I start to have faith in humanity, I ruin it by driving to work between 7 and 8 am.
    20. Re:No - there are plenty of safer alternatives by uniqueUser · · Score: 2, Interesting

      In the same way that having a seat belt and an air bag in my car, doesn't change my driving habits

      I consider myself a safe driver. Seat belts and air bags don't really affect my driving habits either (as far as I know). But what If there was a 7 inch (~18cm) spike sticking out of your steering wheel and 100lbs (~45kg) of high explosives attached to both bumpers, would your driving habits change? Me? Maybe. Sometimes a little danger can make things a little safer. I once heard of a study that showed some poorly painted and poorly lit roads had an increased accident rate when lighting was added and the yellow lines were re-painted. Apparently people began speeding b/c of the perceived increase in safety. I don't remember the source. Maybe Uncle Google can help me later, but I have to get back to work now.

      --
      GENERATION 25: The first time you see this, copy it into your sig on any forum and add 1 to the generation. Social exper
    21. Re:No - there are plenty of safer alternatives by e9th · · Score: 2, Insightful

      strncpy() always bothered me. If len is too short, dst winds up unterminated, and if too long, as you say, you have a bunch of extra nulls at the end. What was the point of that? "Oh, we'll null fill it in case strlen() et al. miss the first one?"
      It would have been nicer if it returned the number of non-null bytes copied, so you could do a quick compare with len to check for the unterminated case.

    22. Re:No - there are plenty of safer alternatives by Duhavid · · Score: 5, Insightful

      It still will not help.

      If they are a sloppy enough programmer not to look at what is going on, and to ensure the size of the destination, they will be sloppy enough to use the same dratted variable in both spots, drool all over the keyboard and move on to the next sloppy bit of code.

      --
      emt 377 emt 4
    23. Re:No - there are plenty of safer alternatives by Com2Kid · · Score: 1

      If you're a competent programmer then nothing is unsafe, but obviously there are a lot of stupid programmers out there who make fundamental mistakes fucking with memory when they don't understand what they're doing

      Minor correction, if you are a competent programmer who is never tired, stressed out, or pressured to meet deadlines, and who always ensures their code is reviewed by other programmers who are equally blessed, then nothing is unsafe.

      Otherwise, as you said, even the best programmers can make mistakes. Even more so when sleep deprived. :)

    24. Re:No - there are plenty of safer alternatives by Marxist+Hacker+42 · · Score: 1

      Agreed. the original memcpy is as outdated as coding a double-linked list by hand.

      --
      SJW: a person who perceives an injustice, and while correcting it, commits a greater injustice.
    25. Re:No - there are plenty of safer alternatives by dhavleak · · Score: 3, Insightful

      Right -- but a static analysis tool can catch precisely that behavior at compile time.

    26. Re:No - there are plenty of safer alternatives by buchner.johannes · · Score: 3, Funny

      I'm not saying you can't get yourself into trouble with inappropriate use of memcpy(3), but buffer overruns aren't the go-to threat every time.

      Didn't we already defeat the goto threat?

      More to the point, if the developer doesn't know what memcpy does and how to use it correctly ... I mean ...
      You might aswell write the 3 lines of code behind memcpy yourself.

      --
      NB: The message above might reflect my opinion right now, but not necessarily tomorrow or next year.
    27. Re:No - there are plenty of safer alternatives by strangepics · · Score: 1

      Better yet user better, more convenient string APIs in the first place. One of them is in libowfat. As you pointed out strn* doesn't protect you from buffer overflows. There are a mighty fine number of good programmers who you'd call braindead. People make mistakes, and if an API helps in that regard then that API is better than the stdio garbage. That's why OpenBSD uses strl* functions instead of strn*.

    28. Re:No - there are plenty of safer alternatives by makomk · · Score: 4, Interesting

      If you're a competent programmer then nothing is unsafe, but obviously there are a lot of stupid programmers out there who make fundamental mistakes fucking with memory when they don't understand what they're doing. What Microsoft is trying to do here is to eliminate a low hanging fruit of software security that has led to hundreds if not thousands of buffer overflow conditions and associated vulnerabilities/exploits.

      The trouble is, it doesn't. Banning functions like strcpy made sense, because they were nearly always unsafe to use. On the other hand, if you're memcpying too much data for the destination, there's probably something more fundamentally wrong with your code. This, at best, conceals the bug by truncating the copy - leading to unpredictable issues later in execution instead.

    29. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      Lame story (Trying for flamebait here?)

      Indeed. Perhaps Ulrich Drepper was the actual submitter of this story?

    30. Re:No - there are plenty of safer alternatives by msuarezalvarez · · Score: 1

      memcpy_s's buffer size argument should be used for the actual size of the destination buffer. It shouldn't be variable based on user input / program flow, and can likely be determined at compile time.

      No, it cannot.

    31. Re:No - there are plenty of safer alternatives by dannannan · · Score: 3, Insightful

      Technically one size argument is enough, but in a large enough software project the code that allocates the destination buffer is maintained separately from the code that copies into it. Any failure in communication (e.g. building against an outdated library) will lead to someone's linker writing a binary with code that will overrun a buffer.

      With an explicit destination size parameter, the buffer copy code is no longer as sensitive to changes at the allocation site. A breakdown in communication will lead to a binary that produces a controlled runtime error instead of a buffer overrun.

    32. Re:No - there are plenty of safer alternatives by Chris+Burke · · Score: 1

      You're interpreting 'unsafe' to mean 'possible to exploit/crash'. I think the parent was taking it to mean 'likely to lead to exploitable/crashable code'. You can hardly argue about that. Just look at the number of sprintf/strcpy security vulnerabilities compared to std::string-caused vulnerabilities.

      Well yeah I am trying to consider the likelyhood. The question is, how likely is it that you fail to properly determine the size of the destination buffer? That probability is the same as the probability that you perform an unsafe memcpy(), and the same probably that you perform an unsafe memcpy_s(). In other words, it changes nothing regarding the likelihood of a bug.

      --

      The enemies of Democracy are
    33. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      Automated testing is a key practice for software development that's almost never used properly. Why do you think Microsoft constantly has issues? A majority of the problems are things they never tried to test for (because it was exceedingly complex given their design) or never thought about testing for.

      Rationalized testing is a very poor substitute to an automated test cycle. It's something that Europeans do constantly, and they often have weird problems. You need to test the binaries you release to your customers or you've never really tested anything. The best method for doing that is to either embed the tests into the code or create a framework that allows for unit, integration and system level testing.

    34. Re:No - there are plenty of safer alternatives by kv9 · · Score: 1

      drool all over the keyboard and move on to the next sloppy bit of code.

      that sounds like most people at my workplace.

    35. Re:No - there are plenty of safer alternatives by msuarezalvarez · · Score: 1

      Sometimes a little danger can make things a little safer. I once heard of a study that showed some poorly painted and poorly lit roads had an increased accident rate when lighting was added and the yellow lines were re-painted.

      That is actively done in Norway: there are some streats where they purposely remove all markings, even the separation between the street and the sidewalk.

    36. Re:No - there are plenty of safer alternatives by George+Reilly · · Score: 4, Informative

      There's nothing unsafe about printf (since compilers started doing format type checking), as long as you don't use user input as the format string. To print user input, you use printf("%s", user_input).

      %n writes to the stack. It's disabled by default in VS2005 onwards. More at http://weblogs.asp.net/george_v_reilly/archive/2007/02/06/printf-n.aspx and http://julianor.tripod.com/bc/formatstring-1.2.pdf

      --
      /George V. Reilly
    37. Re:No - there are plenty of safer alternatives by ckaminski · · Score: 1

      Which is simply avoiding the fact that C and C++ arrays are raw pointers, that while powerful, provide no context on bounds. I'm not one for demanding they enforce bounds checking, but add the capability to have a .length property on a naked pointer when say, I enable RTTI, then

      1. there's no arguments about what the size represents, the size of the data type [sizeof()] or the number of bytes allocated
      2. I can choose to pay the penalty for having secure and more reliable code.

      Oh, and give me decent java-style reflection capabilities. Fix the name mangling, once and for all.

    38. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      Why do people do printf("%s", user_input)? Is it just because they don't know puts() exists? Is there any advantage over puts(user_input)?

      I suspect the printf version will be slower since you are passing more parameters and the function is more complicated.

    39. Re:No - there are plenty of safer alternatives by Ciaran+Power · · Score: 3, Insightful

      That's physically impossible, even given infinite time. Read up on the halting problem.

      No it's not. A computer is not a Turing machine - it has finite memory (=> finite # of states), an algorithm has to halt or visit a state it's already been in.

      And to expand on the GP for those that didn't RTFA, they replaced Memcpy with a memcpy that forced you to state the size of the destination buffer, which is a constant time operation, and a much needed one. So this only forces C coders to make their code a little more clear.

      Fair enough, well done MS. But their new memcpy can be lied to (memcpy_s(dst, 9999, src, 40)) and guys who aren't keeping track of (and checking) their remaining destination size are the guys likely to lie to memcpy_s

    40. Re:No - there are plenty of safer alternatives by Chris+Burke · · Score: 4, Insightful

      What Microsoft is trying to do here is to eliminate a low hanging fruit of software security that has led to hundreds if not thousands of buffer overflow conditions and associated vulnerabilities/exploits.

      They might be trying, but they are failing, because the mistake that leads to the error in the first place (miscalculating destination buffer size) has the same effect (buffer overrun) whether you use memcpy() or memcpy_s().

      --

      The enemies of Democracy are
    41. Re:No - there are plenty of safer alternatives by shutdown+-p+now · · Score: 1

      So what's unsafe about memcpy()? You explicitly specify the number of bytes to copy. If that number of bytes is greater than the known size of the destination buffer, then you've got a problem that simply adding a second 'size of dest' paramater to the copy won't fix because you already screwed the pooch on figuring that out now didn't you?

      No, you screwed on figuring out the amount of bytes called. The other parameter on memcpy_s is the size of destination buffer, nothing more. Ideally, when dest is an array (which it will usually be), it should be sizeof(dest).

    42. Re:No - there are plenty of safer alternatives by Jeremi · · Score: 1

      But what If there was a 7 inch (~18cm) spike sticking out of your steering wheel and 100lbs (~45kg) of high explosives attached to both bumpers, would your driving habits change?

      Most likely you'd refuse to drive the car... or if the dangers weren't too obvious, you'd forget about them in a week or two.

      Of course, none of this would prevent another driver from slamming into you.

      --


      I don't care if it's 90,000 hectares. That lake was not my doing.
    43. Re:No - there are plenty of safer alternatives by ToasterMonkey · · Score: 1

      If people assume that the safety measures in their car will prevent them from being killed, they'd likely accept an accident instead of trying to avoid it.

      I think I know where you were really going with this, but accepting that you will crash (safety measures easing that) and exercising every last bit of control to minimize damage is a better strategy for everyone than trying to avoid an accident at all costs which could result in panicky, fearful, uncontrolled movements. Imagine how many more accidents would result in flipped, spun out cars because panicked drivers tried to avoid being impaled :P

    44. Re:No - there are plenty of safer alternatives by Prof.Phreak · · Score: 1

      Exactly! You want to copy n bytes from src to dest. Why should the -size- of the buffers matter at all?

      --

      "If anything can go wrong, it will." - Murphy

    45. Re:No - there are plenty of safer alternatives by Your.Master · · Score: 1

      The most obvious reason (aside from being unaware of puts) is that puts appends a newline, which is not necessarily desirable.

      Also, it's extremely unlikely for the overhead of the printf version to matter in this sort of situation. That's basically an argument from premature optimization.

    46. Re:No - there are plenty of safer alternatives by Opportunist · · Score: 2, Insightful

      So copying with the destination buffer size specified makes it safe? How so?

      If I knew that the value I want to copy won't fit into the destination buffer, I wouldn't copy it there. Simple as that. Oh, because the size of the source might be variable? Then maybe the coder should do a size_ssize_d?size_s:size_d as the size argument. Taking a variable that isn't under the coder's full control as a size in any memory manipulation operation is asking for trouble anyway.

      Do you think it will be safer now that you "force" the programmer to specify the maximum destination size? If people are sloppy enough to not check sizes, they'll simply pass the same parameter twice and the security you add is zero.

      --
      We used to have a Bill of Rights. Now, with the rights gone, all we have left is the bill.
    47. Re:No - there are plenty of safer alternatives by GargamelSpaceman · · Score: 1

      They need to use libraries that make this shiznit higher level in almost all cases. memcpy_s isn't going to prevent anything. It's corporate bs. In the few cases where someone really needs to use memcpy instead of relying on a library they should by all means use it, but they should have to explain their need and the benefit over using a higher level wrapper to lots and lots of people.

      --
      ...
    48. Re:No - there are plenty of safer alternatives by ZerothAngel · · Score: 2, Informative

      Have a look at strlcpy. It's non-standard, sure, having originated in OpenBSD. But it can now be found in the libc of all the *BSDs, Mac OS X, and even Solaris.

      It guarantees the destination is always nul-terminated and it makes it easy to check if your destination buffer was short.

    49. Re:No - there are plenty of safer alternatives by DamnStupidElf · · Score: 3, Informative

      So why is strncpy in the banned function list?

      I think this is just Microsoft trying to embrace and extend. There's no better way to do that then making most existing C and C++ code invalid. The quickest alternative, of course, is to write it in C# or some other embraced language.

      Hypocritically, Microsoft did NOT add memset to the banned list despite it having almost exactly the same problems as memcpy. Why? Almost every MSDN example begins with "memset(somestruct,0,sizeof(somestruct))" and invalidating every MSDN example would probably look bad.

      As you pointed out, the size of the destination buffer makes no sense when dealing with pure pointers. Often memcpy is used to move memory around inside larger buffers, which completely invalidates memcpy_s as a safe replacement. memcpy is also often used to copy smaller buffers into larger ones, and accidentally copying the uninitialized (or carefully crafted by some exploit) data that comes after the source object can be just as dangerous. The correct replacement, memcpy_overkill(void *source_object, size_t source_size, size_t source_offet, void *dest_object, size_t dest_size, size_t dest_offset, size_t count) is what they're REALLY looking for, but this is impractical primarily because of the heavy use of context-less pointers (to objects within arrays, or within some other structure; the void * in memcpy's prototype hints at further possibilities) in C and C++.

    50. Re:No - there are plenty of safer alternatives by TemporalBeing · · Score: 2, Informative

      memcpy_s's buffer size argument should be used for the actual size of the destination buffer. It shouldn't be variable based on user input / program flow, and can likely be determined at compile time.

      Obviously you have never made a parser of any kind. Any time you read a file in, or use a data stream (cin, cout, cerr, etc.), and many more situations (printf, aprintf, aprintf, etc. not to mention document editors, web browsers, etc) you need to be able to have a dynamically sized buffer to at least manage the data between states.

      Now, if you can always guarantee that you'll read a file with the same exact format every single time you run the application, then yes, you can determine it at compile time.

      However, most applications are more like web browsers in that respect - their input changes every time they run; the format changes. (Think of typing in your post - is there any way the computer could have predicted how much text you'd type? Or the server that it would receive that amount of text from you? Or...the list goes on.)

      Please turn in your nerd badge as the XmlHttpRequest hits you while you close the page...

      --
      Truth is like the sun. You can shut it out for a time, but it ain't goin' away. - Elvis Presley (source: imdb.com)
    51. Re:No - there are plenty of safer alternatives by TheLink · · Score: 2, Insightful

      > Drivers are going to try to drive safer with a steel spike in their face instead of a friendly pillow

      When it comes to programming languages, that approach just means either lots more dead or broken code, or a lot less code AND a lot less good code.

      There's a higher percentage of C programs where "an attacker can execute arbitrary code of the attacker's choice", compared to say Java or Python programs. Just a look at Bugtraq over the years.

      I'm half joking but there might be fewer than 10 people in the world who can write secure, reliable AND useful C programs (useful to more than just one person ;) ). I'm not one of them.

      --
    52. Re:No - there are plenty of safer alternatives by James+Skarzinskas · · Score: 5, Funny

      In an effort to "one-up" Microsoft, Apple promises to replace their own memcpy() with one that not only does not require a size for the destination buffer, but does not require a destination buffer at all. While Apple programmers call the move "totally pointless" and "absolute proof of functional retardation", Steve Jobs has simply responded, sagely, that the future of Apple development is through so-called "intuitive APIs". It just works.

    53. Re:No - there are plenty of safer alternatives by MHolmesIV · · Score: 1

      Unfortunately, the size_t argument is only the number of bytes to copy, it has nothing to do with the size of the destination buffer.

    54. Re:No - there are plenty of safer alternatives by strangepics · · Score: 2, Interesting

      Also take a look at the excellent stralloc which is also part of libowfat.

    55. Re:No - there are plenty of safer alternatives by imp · · Score: 1

      This assumes that those binaries are recompiled.

      assert(sizeof(foo) == sizeof(bar)) (or the compile time variations) is just as effective...

    56. Re:No - there are plenty of safer alternatives by Impy+the+Impiuos+Imp · · Score: 1

      Umm, I don't know for sure, but various lint type tools do things like that already. It would not surprise me if one of them checked if the size parameter was = the size of both the dest and src.

      In any case, you really want a language that would check that dynamically at runtime since many times, you don't actually know the buffer size if it wasn't allocated locally. This is inefficient, to be sure, but would really only be useful for debug builds anyway.

      --
      (-1: Post disagrees with my already-settled worldview) is not a valid mod option.
    57. Re:No - there are plenty of safer alternatives by wassabison · · Score: 1

      lol, And them someone makes foo and bar dynamic, and for most implementations that will always be true. So do you write overflows for a living?

    58. Re:No - there are plenty of safer alternatives by parlancex · · Score: 5, Insightful

      I know you were kidding, but I'd like to point out that the internal implementation of memcpy on many platforms will be much faster than the equivilent C using a loop for large copies, including x86/64 due to the use of architecture specific instructions designed to facilitate the operation that most compilers probably don't use even on the highest optimization levels.

    59. Re:No - there are plenty of safer alternatives by dhavleak · · Score: 1

      You're making the assumption that this change is at the application level. What about at the OS level where you don't want to be calling managed APIs (not managed in a conventional sense, but in the sense of "make this shiznit higher level") - you can't afford performance penalties at that level.

    60. Re:No - there are plenty of safer alternatives by jd · · Score: 5, Insightful

      Whilst you are correct, if Microsoft is going to essentially replace the standard C library with one that has an incompatible API, why not just call it a new library and have done with it?

      Or, better yet, if security really was the goal, develop a C-like language that was secure by design?

      By simply making things awkward for people to write portable code, all they do is ensure that there are multiple code bases for projects (which increases the opportunity for error) or ensures that people won't write portably. Which is a more likely goal, given who we are talking about.

      --
      It's a small world and it smells funny; I'd buy another if it wasn't for the money; Take back what I paid (SoM)
    61. Re:No - there are plenty of safer alternatives by nwanua · · Score: 1

      int len = N;
      void *ptr = malloc( len ); ...

      len *= 2;
      ptr = realloc (ptr, len);

      that's one way to deal with dynamic input... but as the parent was saying, you should keep track of len as you memmov, memcpy. I don't think anyone was suggesting static char ptr[N] as the solution for dynamic memory requirements. OTOH If you could guarantee that you'd never attempt to buffer more than N bytes (regardless of how large/varied/dynamic) the input is, then this also works.

      The point is: if you're going to use a glorified assembler, you'd better keep track of where you're poking and peeking.

    62. Re:No - there are plenty of safer alternatives by drew · · Score: 3, Insightful

      I understand the problem you are describing, but I fail to see how this solution addresses it. If there is already a disconnect between the programmer doing the copying and the programmer doing the allocating, then making the programmer doing the copying repeat himself is not going to fix the problem.

      The only problem this function solves is buffer over flows caused by a programmer calculating a number of bytes to copy at runtime (e.g. by reading it from a Content-Length header) and failing to check the calculated value against what he believes is the actual size of the buffer. If the value that he believes to be the size of the buffer is wrong, changing from memcpy to memcpy_s will not catch the mistake. In other words, changing from memcpy to memcpy_s will only protect against sloppy programmers, and if they don't understand what the function is supposed to be protecting them from (which is likely) they'll probably just use the same value for copy_size and dst_size anyway (or switch to memmove), which will completely defeat the purpose of blacklisting memcpy in the first place.

      Not to mention, if you're doing any pointer arithmetic and writing to an offset some number of bytes past *buffer, then passing the size of *buffer doesn't really help, unless the function is smart enough to know that (I don't see how it could be unless we pass that as a parameter as well), or the user is smart enough to calculate the remaining size of *buffer. If the user is one of the sloppy programmers that this function is meant to protect against in the first place, I think that is highly unlikely, don't you?

      --
      If I don't put anything here, will anyone recognize me anymore?
    63. Re:No - there are plenty of safer alternatives by Tweenk · · Score: 1

      And them someone makes foo and bar dynamic

      What? foo and bar are types. If their sizes do not match there is an ABI break and your program will not work anyway. Go learn some C.

      --
      Those who would give up liberty to obtain working drivers, deserve neither liberty nor working drivers.
    64. Re:No - there are plenty of safer alternatives by niteice · · Score: 2, Insightful

      Or, better yet, if security really was the goal, develop a C-like language that was secure by design?

      And then why don't you make it compile to non-native code, so you can do code analysis at runtime? Might as well give it a good standard library that uses all the features so people would try writing stuff. Of course, you can't name it C then, maybe you should give it a catchier name with some punctuation or other pun on the language.

      Hey, wait a minute...

      --
      ROMANES EUNT DOMUS
    65. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      No it's not. A computer is not a Turing machine - it has finite memory (=> finite # of states), an algorithm has to halt or visit a state it's already been in.

      This is about the undecidability of the halting problem, not about the required testing of a finite machine. The parent was little misleading about that, though. Since most programs have an environment, the problem is moot anyway.

    66. Re:No - there are plenty of safer alternatives by mustafap · · Score: 3, Interesting

      >Or, better yet, if security really was the goal, develop a C-like language that was secure by design?

      Or, better yet, if security really was the goal, use Ada.

      There, fixed that for you :o)

      --
      Open Source Drum Kit, LPLC deve board - mjhdesigns.com
    67. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      And them someone makes foo and bar dynamic

      So then the assertion becomes dynamic. How hard is that?

    68. Re:No - there are plenty of safer alternatives by LordKazan · · Score: 1

      the halting probably is still unsolvable on a real world computer.

      should i really have to explain that to you?

      --
      If you cannot keep politics out of your moderation remove yourself from the Mod Lottery.. NOW!
    69. Re:No - there are plenty of safer alternatives by bluefoxlucid · · Score: 1
      memcpy(dst, src, len) {
      int i;
      for (i = 0; i < len; i++) {
      dst[i] = src[i];
      }

      Versus:

      memcpy_s(dst, dlen, src, slen) {
      int i, len;
      len = slen;
      if (dlen < slen)
      len = dlen;
      for (i = 0; i < len; i++) {
      dst[i] = src[i];
      }

      Now look at these two functions. memcpy_s() is not predictable: it will either copy src to dst or it won't. With memcpy(), you can reasonably expect that dst will contain src; but you must ensure that dst can hold src.

      What it boils down to is this: With memcpy_s(), you have to make checks to determine if dst is as long as src, and handle partial data copies accordingly, lest something strange and unexpected happens. With memcpy(), on the other hand, you have to make checks to determine if dst is as long as src, and handle partial data copies accordingly, lest something strange and unexpected happens!

    70. Re:No - there are plenty of safer alternatives by lgw · · Score: 1

      #define memcpy_s(dst, dlen, src, slen) memcpy(dst, src, min(dlen, slen))

      Now all my code is magically safe from buffer overruns! The Microsoft SDL is a complete load of crap. You can only fix bad programming by fixing bad programmers. Send anyone who finds this stuff hard off to program in C#/Java. It takes a certain mindset to do low level programming, and there are more high-level programming jobs in any case.

      --
      Socialism: a lie told by totalitarians and believed by fools.
    71. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      Yeah... I've seen the result of this. It warns people that write this code:

      strcpy(target, source)

      to write this code instead (actual example!):

      strncpy(target, source, strlen(source));

      Yeah... that'll really help.

    72. Re:No - there are plenty of safer alternatives by bored · · Score: 3, Interesting

      So why is strncpy in the banned function list?

      Because strncpy() is as bad as strcpy(). The problem lies in the fact that if the source string is longer than the destination len, then strncpy simply stops the copy without writing a NULL. The next str* function used on the string is likely to crash.

    73. Re:No - there are plenty of safer alternatives by bluefoxlucid · · Score: 1

      What you just said makes absolutely no sense. You are basically saying that programming is unreliable and unpredictable until compile time, and that logical behavior can be modified by the compiler/linker tool chain in a properly functioning environment. Everything is deterministic; that you don't know how big the destination buffer is doesn't negate the fact that the destination buffer is created and destroyed by some code. If you have no way of knowing, at any point, that said buffer hasn't been adjusted; then you effectively have no way of knowing its size or validity. By the same token, you must always have some way of getting the destination buffer's size (read: any library code that passes you a buffer must either ask for its minimum size and respect that, or expose its size when asked), or for all you know it's a 0 length buffer, thus is not useful.

    74. Re:No - there are plenty of safer alternatives by bluefoxlucid · · Score: 1

      No language is secure by design. Languages address potential problems by design, but they are not secure.

    75. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      Think a server taking input of unknown length would realloc for each byte over it's original buffer length? Or could it be buffering using a static buffer (length determined at compile-time), and/or realloc-ing the final destination by a set amount (determined at compile-time) as it needs to?

      In any case, I don't think GP meant you couldn't use dynamically sized buffers. And _obviously_ the size of a dynamic buffer can't be determined at compile time. But there are many cases where static buffers and/or predictably-growing dynamic buffers make sense, and the dlength for those memcpy calls can be determined at compile-time.

    76. Re:No - there are plenty of safer alternatives by bluefoxlucid · · Score: 1

      Most Java J2EE programs have security holes. That some get fixed doesn't mean new ones don't get introduced. Most are of the SQL injection or other improper input parsing variety. oh wait....

    77. Re:No - there are plenty of safer alternatives by prockcore · · Score: 1

      So what happens when dest is a pointer to the middle of an array?

      Odds are that everyone will just take memcpy(dest,src,n); and change it to memcpy_s(dest,n,src,n);

    78. Re:No - there are plenty of safer alternatives by TemporalBeing · · Score: 1

      There's far more to using memcpy than reallocating memory buffers. You may go from compile-time buffers to fully dynamic buffers or vice-versa, (realloc() won't help you there) or you may go to existing already allocated memory....

      Regardless (we do agree) you do need to keep track of what you're doing. And ANY good program(mer) does.

      Personally, I detest Microsoft's "Secure" style here. It's not standards based, and it breaks portability like crazy. In some ways its nice they are doing this, but they should have it disabled by default per warnings, or at least let people set via a compiler flag (instead - accessible as part of the project, even if its turned on by default in the settings) whether you want to do that and give a warning about portability as a result. That, for starters, would be a lot more helpful than their current implementation.

      --
      Truth is like the sun. You can shut it out for a time, but it ain't goin' away. - Elvis Presley (source: imdb.com)
    79. Re:No - there are plenty of safer alternatives by prockcore · · Score: 1

      memcpy doesn't verify the size of the receiving buffer is large enough for the copy, so it is possible to overrun the buffer.

      Neither does memcpy_s.

      This does the exact same thing as memcpy_s:


      #define memcpy_s(d,dn,s,sn) memcpy(d,s,(dn)<(sn)?(dn):(sn))

    80. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      my new 4 param memcopy.
      size_t memcpy_s(void *pDest, size_t unDestSize, void *pSource, size_t unSourceLength);

      my usage of said function
      memcpy_s(pDest, 256*256*256*256, pSource, unSourceLength);

      I pass and am 'technically' still correct code. What would stop someone from abusing it this way?

      Taking it away is just dumb too as you can just write one... Or copy it out of the old .c libraries...

      The horse is out of the barn already you are only putting up roadblocks. And not effective ones.

    81. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      With memcpy_s() ... something strange and unexpected happens. With memcpy() ... something strange and unexpected happens!

      The difference is that memcpy_s() won't result in a buffer overrun. Yes, not having all the data in dst will result in something strange/unexpected, but it won't be a security hole.

    82. Re:No - there are plenty of safer alternatives by MichaelSmith · · Score: 1

      The worst example I saw went like this:

      char *buffer = malloc(200);
      memcpy(buffer,message,2000);
      send_message(buffer);
      free(buffer);

      It only occasionally caused a crash because there was a lot of unused space on the heap.

    83. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      That is actively done in Norway: there are some streats where they purposely remove all markings, even the separation between the street and the sidewalk.

      Which is a really stupid idea, because instead of levelling the playing field, it amplifies the differences between Grandma in her 4,000-pound Buick and a stereotypical 20-year-old kid with fast reflexes and no sense of his own mortality, whose initials are on the high-score list on every arcade game in town. He doesn't need the stripes and lights, and won't drive any differently with or without them. Grandma does.

      I'm closer to "Grandma"'s level, myself, and I hate driving on roads with ambiguous or missing markings. I lose situational awareness at the drop of at hat. If you want me to be a safe driver, paint some stripes.

    84. Re:No - there are plenty of safer alternatives by vux984 · · Score: 1

      This, at best, conceals the bug by truncating the copy - leading to unpredictable issues later in execution instead.

      No, at best, it throws an exception, leading to an immediate fail the moment its attempted. Resulting in an relatively easy problem to fix.

    85. Re:No - there are plenty of safer alternatives by bluefoxlucid · · Score: 1

      Unless you fail to handle the situation of partial data, read garbage, fault out of the function, and hand over administrative access by some unpredicted magic. It's happened.

    86. Re:No - there are plenty of safer alternatives by Nakoruru · · Score: 1

      Given a Turing machine with a finite memory and an input it will either halt (accept or reject), eventually enter a state it has been in before (infinite loop, so reject), or attempt to enter a state that requires more memory than it has (we can take that as a "reject"). Therefore it is possible to know if the machine accepts or rejects in all cases.

      This cannot be practically applied because the amount of space and time required even for small machines is still too large but it does make the point that the halting problem depends on the infinite nature of the Turing machine.

    87. Re:No - there are plenty of safer alternatives by LordKazan · · Score: 1

      go look up the halting problem. you can construct an algorithm that creates a contradiction.

      http://en.wikipedia.org/wiki/Halting_problem

      --
      If you cannot keep politics out of your moderation remove yourself from the Mod Lottery.. NOW!
    88. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      Any static analysis tool worthy of the name should be able to do this already. The extra argument seems pretty worthless on that front.

      That said, the extra argument might be useful to prevent errors at run time, when the constraints on the sizes passed are too complicated for the machine to verify automatically.

    89. Re:No - there are plenty of safer alternatives by Nakoruru · · Score: 1

      But the proof depends on not being able to know if the Turing machine is done or not. A Turing machine with finite memory does not have that problem.

      I just gave you a proof. It wasn't formal, but it covered all the cases.

    90. Re:No - there are plenty of safer alternatives by thethibs · · Score: 1

      Aaaugh! Waddya think you're using? QBasic?

      len = (dlen<slen)?dlen:slen;

      --
      I'm a Programmer. That's one level above Software Engineer and one level below Engineer.
    91. Re:No - there are plenty of safer alternatives by thethibs · · Score: 1

      I've got to update my tools. When did C get min()?

      --
      I'm a Programmer. That's one level above Software Engineer and one level below Engineer.
    92. Re:No - there are plenty of safer alternatives by Nakoruru · · Score: 1

      I just thought of a simple proof that the halting problem does not apply to Turing Machines with finit e memory (which means it isn't really a Turing Machine, but oh well).

      The input of a Turing machine is the initial contents of the tape. Therefore a Turing Machine with finite memory only has a finite number of possible inputs. It is possible for me to simply go through all those possible inputs and mark them as "Accept" or "Reject". Since it is not possible (through diagonalization) to construct an input that is not in my list, I have accounted for every possible input. I can implement HALT by simply consulting my table. All possible finite memory Turing machines and their inputs can be constructed this way, so HALT is implementable for a Turing machine with finite memory.

      QED motherfucker.

    93. Re:No - there are plenty of safer alternatives by chkn0 · · Score: 2, Informative

      Or the server that it would receive that amount of text from you?

      Actually, yes.

    94. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      Nonsense. First of all, there's nothing wrong with writing to the stack. You do that every time you assign to a local (stack-allocated) variable. Second, %n causes printf to write where you tell it to by passing a pointer to int. There's nothing wrong with %n per se. There is, however, a lot wrong when incompetent wannabe programmers do printf(foo) instead of printf("%s", foo) or (better yet) fputs(foo, stdout). In that case, of course a %n in foo will be pretty bad, but so will any other unescaped %.

    95. Re:No - there are plenty of safer alternatives by dhavleak · · Score: 1

      Yeah, you're right -- static analyzers already should (and do) catch these things. But it's still worth it to decouple the thinking (and hence the handling) of the size of the source and destination. i.e. you have that as your prime motive for banning this API, and the static analyzer as the fallback to guard against the bad habit of just passing in the exact same varabile as source size and destination size.

      Remember, ultimately all of this can be defeated by a programmer who's determined to be insecure/stupid. He/she could just put in some #pragma at that statement that tells the static analyzer "this is cool -- don't throw an alert when you see it" and then pass in the same variable. i.e. this coder has gone and defeated the purpose of both the banned API list and the static analyzer. So there's no magic bullet for sure. But that doesn't mean you shouldn't make whatever improvements you can -- and this is definitely a Good Thing.

    96. Re:No - there are plenty of safer alternatives by Darinbob · · Score: 1

      A big snag is that memcpy is typically used for buffers, not "objects". With an object you know the size, and often have some other way of copying the data (C++ constructors, structure copying, etc). With buffers though it is more complicated, or even with raw memory regions.

      The size of the destination for the copy won't be the size of the destination buffer, instead you have to take into account the offset into the buffer where the copy will start. The naive programmer that has a bug with memcpy will likely still have a problem with memcpy_s or other solutions if they just pass sizeof(destbuffer)... In other words, the size of the destination is often not a constant known at compile time.

      Memcpy is intentionally a low level function which should not be used at a high level. Much of the time that I use memcpy it is within a function that is intended to provide a safer alternative. So a blanket "omg don't use it!" prohibition disallows using memcpy even where it is useful and vital (ie, I'd hate to implement memcpy_s without it calling memcpy).

      Yes, memcpy has a potential to be unsafe. But just about everything else has that potential. Do we disallow using "uint8_t*" as well, array assignments, function pointers, assembly language, the C language, or anything not running under a virtual machine sandbox?

    97. Re:No - there are plenty of safer alternatives by chkn0 · · Score: 1

      #define min(X,Y) ((X) < (Y) ? (X) : (Y))

      Just be careful with your side effects.

      (gcc-3 had a side-effect safe <? min operator, though it has since been removed.)

    98. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      So, exactly how do you write cross-platform code that copies from 1 memory location into another with a specified number of bytes? I'm curious.

      Cross-platform means: 32/64 bit versions of WinXP, Win 2008 Srv, Linux, Solaris, Irix, HP-UX, AIX, Digital Unix, MacOS, MVS, VAX ... and MS-Dos.

      Please, educate me. It needs to support any legal memory valid.

    99. Re:No - there are plenty of safer alternatives by bluefoxlucid · · Score: 1

      Most arbitrary programmers can read simple C. Fancy operators and vaguely-named functions or functions with subtle differences (strcpy() vs strncpy() with no explanation) are only meaningful to straight C programmers. Some C++ programmers have nfc what strncpy() is because they just use type string (college tends not to teach C anymore, just C++, and absolutely everything is done with C++ STL and avoid any "legacy" C functions like the plague).

    100. Re:No - there are plenty of safer alternatives by setagllib · · Score: 2, Insightful

      Who do you think has to write those high level wrappers? memcpy is one of the most ridiculously popular functions in systems level C/C++ code, especially for copying arrays or sub-arrays, where it can be much faster than a hand-written loop. You can wrap it in a function for every type you need, but that's still a lot of memcpy you have to write properly. Fortunately it's easy and this whole argument is moot.

      --
      Sam ty sig.
    101. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      Perhaps they're banning a generic method in favour of having a lot of utility classes/functions that provide the same functionality for specific types and check for problems in the input. It makes sense in a lot of instances to do this instead of relying on each programmer to individually develop a method to validate his input and generate a block size. It also makes it easier to patch problems later with a single update to a lib function.

    102. Re:No - there are plenty of safer alternatives by InfiniteLoopCounter · · Score: 1

      ...I'd like to point out that the internal implementation of memcpy on many platforms will be much faster than the equivilent C using a loop for large copies, including x86/64 due to the use of architecture specific instructions designed to facilitate the operation that most compilers probably don't use even on the highest optimization levels.

      Actually, when zeroing a large array it can be faster to use a loop because memcpy has to line up blocks of memory as part of it's operation.

    103. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      Like I said in the recent glibc discussion thread on strlcpy the Microsoft C libraries are full of good intentions, but fail miserably at being safer alternatives for most applications.

      In any case, before replacing C functions with known and well understood issues, they should start with C++ and its standard libraries which are inherently insecure miscreants and make up most of their code.

    104. Re:No - there are plenty of safer alternatives by setagllib · · Score: 1

      Which is fine if you don't use it. Disabling it just breaks existing code, not using it in the first place breaks nothing. Using the right code gets the right result. The same applies for almost all standard C functions for which the average (i.e. bad) programmer doesn't read the manpage.

      --
      Sam ty sig.
    105. Re:No - there are plenty of safer alternatives by thethibs · · Score: 1

      I guess I should take that to mean that C hasn't acquired min().

      --
      I'm a Programmer. That's one level above Software Engineer and one level below Engineer.
    106. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      Well, from now on you may still write portable code using memcpy, implement all the buffer checks you like... and then your average Joe will still get a cool "Warning: software uses insecure memcpy()" message.

      Ain't that sweet?

    107. Re:No - there are plenty of safer alternatives by TapeCutter · · Score: 3, Insightful

      "In the few cases where someone really needs to use memcpy instead of relying on a library"

      First of all, memcpy IS a libary call.

      "but they should have to explain their need and the benefit over using a higher level wrapper to lots and lots of people."

      One source tree, many O/S's. Memcpy is a ANSI C library call, I have been using it for more than 20yrs without a problem. IF MS want to pop up a warning that tells me my source will compile on gcc I can't stop them from doing so.

      --
      And did you exchange a walk on part in the war for a lead role in a cage? - Pink Floyd.
    108. Re:No - there are plenty of safer alternatives by parlancex · · Score: 1

      The implementation of the STL is platform dependent but the behavior is (at least it _should_ be) mostly identical so you can be assured that by using memcpy when it is available that it will be the fastest way to copy a large number of bytes on any platform. (The unix based implementation of the STL is in libc and the Windows implementation is in msvcrt.dll)

    109. Re:No - there are plenty of safer alternatives by parlancex · · Score: 1

      ...I'd like to point out that the internal implementation of memcpy on many platforms will be much faster than the equivilent C using a loop for large copies, including x86/64 due to the use of architecture specific instructions designed to facilitate the operation that most compilers probably don't use even on the highest optimization levels.

      Actually, when zeroing a large array it can be faster to use a loop because memcpy has to line up blocks of memory as part of it's operation.

      I don't see how memcpy should ever be used to zero blocks of memory. The best way to do this on Windows platforms is with win32 API function ZeroMemory, who's implementation would be something along the lines of:

      xor eax,eax
      mov edi, dst_address
      lea ecx, [byte_count / 0x04]
      rep stosd
      mov ecx, byte_count
      and ecx, 0x03
      rep stosb

      Where the last 3 instructions could be averted if byte_count was guaranteed to be a multiple of 4. This would be substantially faster than using a loop.

    110. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 1, Insightful

      Congratulations! Your bad programming silently truncates data when the source is too large for the destination. This, of course, is yet another software defect, which may cause your program to behave incorrectly, crash, or be exploitable by an attacker.

      Depending on the application, a truncation may be exploitable by causing a buffer overrun elsewhere in the program. So no, your code is not magically safe from buffer overruns. Perhaps you should be programming in C#/Java, since this stuff is clearly too hard for you.

    111. Re:No - there are plenty of safer alternatives by BZ · · Score: 1

      One would think that the right way to zero memory would be memset, which happens to be portable and is presumably implemented in a very similar way, no?

    112. Re:No - there are plenty of safer alternatives by Alex+Belits · · Score: 1

      int len = N;
      void *ptr = malloc( len ); ...

      len *= 2;
      ptr = realloc (ptr, len);

      ..and then at some point you exceed the amount of available memory, ptr is assigned NULL, and position of your actual allocated buffer is lost forever. And it takes up at least half of memory you have available for emergency cleanup, so all you can do is to call exit() or abort() right now.

      I hope, you will be never allowed to write software that other people rely on.

      --
      Contrary to the popular belief, there indeed is no God.
    113. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      Look, if he was too dumb to understand how libraries work or why they exist, it's not worth explaining to him. He's not going to understand what you're talking about.

    114. Re:No - there are plenty of safer alternatives by Fujisawa+Sensei · · Score: 1

      Whilst you are correct, if Microsoft is going to essentially replace the standard C library with one that has an incompatible API, why not just call it a new library and have done with it?

      The ultimate goal I would have to guess would be to ensure incompatibility.

      First they change the C language so that it is incompatible while claiming that its more secure.

      Then the patent those changes, and use their army of lawyers to try and prevent compatibility from competition like Wine.

      --
      If someone is passing you on the right, you are an asshole for driving in the wrong lane.
    115. Re:No - there are plenty of safer alternatives by GargamelSpaceman · · Score: 1

      In almost all cases there would be no performance penalties. In a few cases there would be slight performance penalties. In a very very few cases, there would be significant performance penalties. In those cases use whatever works and be very careful.

      --
      ...
    116. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      Just make yourself a macro and don't worry about it.

      As for creating the C-like language, in theory, that's their goal with C++.NET. Use the .NET Framework when you can get away with it, and hit the metal when you need to do it.

    117. Re:No - there are plenty of safer alternatives by GargamelSpaceman · · Score: 1

      I should have said a higher level library. If you're doing high level programming in any language use high level libraries. If you truely need to get down to the bare iron for some COMPELLING reason other than 'I just felt like it' then use lower level libraries.

      --
      ...
    118. Re:No - there are plenty of safer alternatives by jd · · Score: 1

      That, I fear, seems very likely to me.

      --
      It's a small world and it smells funny; I'd buy another if it wasn't for the money; Take back what I paid (SoM)
    119. Re:No - there are plenty of safer alternatives by jd · · Score: 2, Informative

      Perhaps that was a little bit ambiguous of me. What I was referring to were programming languages which reduce the possibility of error (eg: ADA) and/or which are designed to enforce good programming practice and rigorous standards (eg: Occam).

      I consider these to be "secure by design" because they were designed to make the more common security flaws impossible and were also designed to make it possible to validate the software. (Both, if I understand the histories correctly, were linked to military efforts to produce highly robust, highly secure code.)

      --
      It's a small world and it smells funny; I'd buy another if it wasn't for the money; Take back what I paid (SoM)
    120. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      We haven't even specified the design of "make this shiznit higher level" -- those are very bold claims to make without that.

    121. Re:No - there are plenty of safer alternatives by wassabison · · Score: 1

      In your code what, dictated foo and bar were TYPES? You can use sizeof for arrays as well as types. This is problematic when some one changes the array to a dynamic array.
      char foo[4];
      char * bar;
      bar = malloc(sizeof(char)*16);
      printf("%d %d", sizeof(foo), sizeof(bar));
      assert(sizeof(foo) == sizeof(bar));
      memcpy(foo, bar, sizeof(bar)); //What just happened???

      I think you need to go and learn some C. Or at least common mistakes that people will make that Microsoft is trying to avoid, like using sizeof on a dynamically allocated piece of memory.

    122. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      Mod parent up (well he's already at 5 , but it should go higher ;)

      All this so called "safe" version of memcpy is going to accomplish is to hide actual problems in the program. If your destination buffer isn't big enough to receive data you intended to copy, then you *have* a problem anyway. Truncating the copy isn't going to solve it in 99% of the case.

    123. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      In an effort to "one-up" Microsoft, Apple promises to replace their own memcpy() with one that not only does not require a size for the destination buffer, but does not require a destination buffer at all. While Apple programmers call the move "totally pointless" and "absolute proof of functional retardation", Steve Jobs has simply responded, sagely, that the future of Apple development is through so-called "intuitive APIs". It just works.

      [self Additionally: [[[[[[[[[[it will] have] lots] and] lots] of] brackets]

    124. Re:No - there are plenty of safer alternatives by Omni-Cognate · · Score: 1

      Or even a simple drool detector built into the keyboard.

      --

      "The Milliard Gargantubrain? A mere abacus - mention it not."

    125. Re:No - there are plenty of safer alternatives by Omni-Cognate · · Score: 1

      I'm assuming this was due to a typo on the first line (and presumably no code reviews). With memcpy_s and the same development practices, this would most likely become:

      char *buffer = malloc(200);
      memcpy(buffer,2000,message,2000);
      send_message(buffer);
      free(buffer);

      , which would behave exactly the same and illustrate the point many people here are making about this really not fixing the supposed insecurity. The reason the code you show crashed is not that memcpy takes no destination size parameter. The reason is that the code contained an obvious typo that nobody noticed because there were no formal code reviews.

      --

      "The Milliard Gargantubrain? A mere abacus - mention it not."

    126. Re:No - there are plenty of safer alternatives by Fish+(David+Trout) · · Score: 1

      Mod parent up!

      So very many programmers tend to forget that strncpy DOES NOT ALWAYS NULL TERMINATE!

      The only time it does is when the source data is shorter than the destination buffer. If the source string is longer than the destination buffer however, then the end result is the string is NOT null terminated, thereby leading to Bad Things(tm) happening whenever some other code does a strlen on the result (or worse, uses the return value from strlen(result) to determine how much data needs to be memcpy'ed somewhere).

      strncpy is bad.

      Use strlcpy (BSD) or MS's strcpy_s instead.

      --
      "Fish" (David B. Trout)
    127. Re:No - there are plenty of safer alternatives by MichaelSmith · · Score: 1

      Well first there is the stupidity of declaring a pointer on the stack, mallocing and freeing before you return when you can just declare buffer as a local variable.

      Second, this was one of about 20 identical functions, each for sending a different message. Each function had exactly the same bug.

      Thirdly, as you point out, a code review would have helped, and we do that today. But we aren't churning the code out today anyway. A subcontractor of ours is though and I noticed the following gem...

      if(status == EXIT) return int;

      ...comitted to cvs and fortunately breaking a build this past thursday. Its my job to do the builds these days you see. When the pressure is on there is no time to review properly.

      We think working in java will help because you can't overflow buffers. But when you have gigabytes (no joke) of java source code it can be hard to track down the bugs which are causing your threads to crash with exceptions.

    128. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      "drool all over the keyboard"

      Really? They can catch that now? Damn those things have gotten good.

    129. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      QED motherfucker.

      Congratulations, Minsky 1967.

      As he himself noted, there are also practical physical problems in the way of appeals to the finite size of state tables, so in essence there may remain a real decidability problem in programs designed around algorithms like those introduced a couple of years earlier by Radó.

      So, sadly, not obviously QED, however it would be pretty damn cool if you could actually demonstrate it, so don't be dissuaded.

    130. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      that sounds like most people at my workplace.

      Perhaps it's time to find yourself an other job?

    131. Re:No - there are plenty of safer alternatives by TheLink · · Score: 1

      But there's probably at least 100x more people who can write J2EE programs without "SQL injection crap" than the number of people who can write C programs without "shellcode injection crap". It's a lot easier to do the "parameterized statements/bind vars/placeholders" thing in Java or Perl than with C. So the C programmers will have both buffer overflow problems and SQL injection problems to deal with.

      Of course we also get 200x more people who write junk in java... :)

      --
    132. Re:No - there are plenty of safer alternatives by TheLink · · Score: 1

      Question: What if we just have a separate stack for data, and a separate stack for code, and do similar things[1] to maintain hygiene aka "code-data separation"?

      Then even if stuff overflows, you don't end up _running_ it.

      [1] If you need to pass jump addresses as parameters, have whitelisted entry points, or pass an item number instead of the address itself.

      Intel and AMD seem to be running out of ideas of what to do with all the zillions of transistors and can't make things faster. Why don't they make it easier for things to be more secure while retaining performance. Having pre-whitelisted entry points for execution might even things easier for cache lookahead.

      --
    133. Re:No - there are plenty of safer alternatives by Snorbert+Xangox · · Score: 1

      strncpy() always bothered me. If len is too short, dst winds up unterminated, and if too long, as you say, you have a bunch of extra nulls at the end. What was the point of that? "Oh, we'll null fill it in case strlen() et al. miss the first one?"

      I heard that the back-story of strncpy() was that it was originally used for filling in fixed length fields in structures that get written to disk (like, say, utmp) or go out on the wire. For that purpose, the absence of automatic null termination of an overlong string is no problem, because the field length itself provides a delimiter on a string that fills the field. This also explains the puzzling null filling behaviour for strings shorter than the destination string length.

      It would have been nicer if it returned the number of non-null bytes copied, so you could do a quick compare with len to check for the unterminated case.

      For that matter, I always wondered why strcat did not return a pointer to the trailing null on the destination string... multiple strcat()s on the same string could run in linear time instead of O(n^2), as well as letting you find how long the destination string was without a separate call to strlen(). It wasn't like returning the pointer to the trailing null (wherever that ended up!) could make strcat() less safe... :^)

      strlcpy() (if you have it) does return the source string length, which is at least more useful than getting a pointer to the destination string as a return value.

      --
      -Snorbert, somewhere in the antipodes
    134. Re:No - there are plenty of safer alternatives by sqldr · · Score: 1

      It's the C programming language which is at fault here. Arrays in C aren't really arrays, they're just pointers. Most modern languages (such as D, which all C++ programmers should investigate) have bounds checking on actual arrays.

      Crippling an important C function is a dumb idea. Firstly, most of the code I write (mostly VST softsynths) isn't subject to any security risks. Who is going to crack a rarely used plugin for a much larger application which probably has holes of its own? Secondly, nine times out of ten, the "count" parameter I pass usually comes from the "sizeof()" function, so it's rather difficult to get that wrong.

      In any respect, kernel aside, Microsoft has a perfectly good overflow-proof language which can be used to write the majority of their applications in. You may have heard of it.. it's called C#/.NET. Effectively, what they are doing is banning the use of an essential C function in programs which actually have to be written in C because .NET isn't low level enough. Oh well. not my problem. Good luck, MS.

      --
      I wrote my first program at the age of six, and I still can't work out how this website works.
    135. Re:No - there are plenty of safer alternatives by annerajb · · Score: 1

      I am a student at a game development school when we started our programming 1 course everybody said to never have warnings on your code and to fix all of them. and they told us about the _s version of printf etc. 3 months ago i started looking into porting all my old code to my new ubuntu desktop. because i want to learn how to make games for linux and was surprised that it didnt compile. now i have to or leave the "unsafe" versions on my code or disable the warning.

    136. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      Almost all shiznit qualifies, even 'OS Level' shiznit. If your code is big enough to be exhibiting mistakes due to premature/unnecessary optimization, you need to 'make this shiznit higher level'

    137. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      Thanks. That makes sense.
      I'm aware of strlcpy(). I discovered that it wasn't universal a few years ago while porting an app from OpenBSD to Debian.

    138. Re:No - there are plenty of safer alternatives by FlyingBishop · · Score: 1

      No it didn't.

      Consider a Turing machine that creates a fractal in finite space. When it reaches the next iteration of the fractal, it begins to consume memory at the beginning. Even though you have finite memory, you cannot make any claims about what that fractal will do over the course of time. Throw in a check so that the machine halts when some substring matches a given search term. You cannot decide if that machine will ever match that search term. It is not possible.

      The Halting problem means, in essence, that there exists no automated test for infinite loops. Obviously, there are trivial ones like "while $true;" However, you cannot build a machine that can tell the difference between an algorithm that is looping infinitely and an algorithm that has not finished. That is the halting problem, and it has nothing to do with infinite space.

      I just realized you're a troll. Good work.

      If not, this is essentially Cantor's diagonal argument for the uncountability of the reals, and people refused to believe that too. Doesn't make it less true.

    139. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      "There are safe versions of memcpy that work just fine and are just as easy to use... "

      Erm, such as?

      OK, I'll come clean - I very infrequently think I've a reason to use memcpy() - but it serves a purpose. Sure, it's dangerous - but so is memset() and bzero() and many other similar functions that write to a number of bytes starting at a specific memory location. What alternative tool do you propose for the (unusual) circumstance where manipulating specific binary messages to, for example, drive hardware?

    140. Re:No - there are plenty of safer alternatives by ukyoCE · · Score: 1

      I haven't done C for a while, but it sounds like memcpy_s eliminates a whole class of buffer overrun errors.

      If you're doing:

      memcpy(dest, source, 10) =
      memcpy_s(dest, 10, source, 10)

      Then yes, memcpy_s hasn't helped you, but it also hasn't hurt you at all.

      But if you're doing
      memcpy(dest, source, SIZE)
      You'll now be doing:
      memcpy_s(dest, SIZE, source, SIZE) //ideally not
      or
      memcpy_s(dest, DESTSIZE, source, SOURCESIZE)

      In the former case, again, you haven't benefited at all. But you're being encouraged to do the latter. In cases where:

      DESTSIZE > SOURCESIZE //could error
      DESTSIZE = SOURCESIZE //could error
      DESTSIZE SOURCESIZE //the memcpy_s function can catch this case and not cause a buffer overrun

      Since that 3rd case is where more buffer overruns come from (it's guaranteed to be wrong), isn't eliminating that whole class of buffer overruns a good idea?

      It's a bit silly to claim "well anyone smart will use memcpy_s anyway if DESTSIZE can be less than SOURCESIZE". Obviously no one sits down and thinks, "I know, I'm going to write a buffer overflow!" It's an accident. Using memcpy_s prevents that accident.

    141. Re:No - there are plenty of safer alternatives by ukyoCE · · Score: 1

      Oops, speaking of accidents, Slashdot ate my <

      The third option was
      DESTSIZE < SOURCESIZE

    142. Re:No - there are plenty of safer alternatives by msuarezalvarez · · Score: 1

      Well, they do measure the outcome of having doing those changes, and have kept them because things have improved. I guess there are granmas in Norway, too, so it musthave not been as bad as you seem to think for them.

    143. Re:No - there are plenty of safer alternatives by LordKazan · · Score: 1

      talk about missing the point.. go back to your theory class

      --
      If you cannot keep politics out of your moderation remove yourself from the Mod Lottery.. NOW!
    144. Re:No - there are plenty of safer alternatives by Adam+Hazzlebank · · Score: 1

      It's the C programming language which is at fault here. Arrays in C aren't really arrays, they're just pointers. Most modern languages (such as D, which all C++ programmers should investigate) have bounds checking on actual arrays.

      D has bounds checking on primitives? That doesn't seem like a great idea, must have a significant performance impact. Sure it prevents buffer under/overruns, but if you want to do that use a container class which does bounds checking.

    145. Re:No - there are plenty of safer alternatives by parlancex · · Score: 1

      memset would be basically the same, except instead of xor eax, eax you would have a small series of instructions to load an 8 bit value in memory into each 8 bits of the 32 bit register eax, which although technically slower it would be extremely meaningless for anything but a very large number of very small buffers.

    146. Re:No - there are plenty of safer alternatives by Darinbob · · Score: 1

      The problem with buffer overflow is not limited to just executing arbitrary data placed on the stack. It can be just as bad to put any data value on the stack as well. For instance, you can overwrite the return address to a function, tweak a web address, change all sorts of local variables, etc.

    147. Re:No - there are plenty of safer alternatives by TapeCutter · · Score: 1

      Simple rule: If you do not know what is in a structure/object then don't use memcpy. A good class library will implement a standard copy member.

      --
      And did you exchange a walk on part in the war for a lead role in a cage? - Pink Floyd.
    148. Re:No - there are plenty of safer alternatives by Anonymous Coward · · Score: 0

      What this does do is make me loose 45 points on my programming project.

      I used printf_s which does not exist in ANSI C and therefore my program did not compile on the schools computers and I ended up with a 55% for a working program despite that mistake. Let me just say I never used Visual Studio after that.

    149. Re:No - there are plenty of safer alternatives by InfiniteLoopCounter · · Score: 1

      One would think that the right way to zero memory would be memset...

      You're probably right here. I had in mind memset when I wrote memcpy.

      To redeem myself for making such a mistake, I would like to point out that, for repeating patterns of initialisation data, it is probably faster to use a partially unrolled loop.

    150. Re:No - there are plenty of safer alternatives by YenTheFirst · · Score: 1

      The parent's point, though, is that the halting problem, and the diagonalization argument, are inherently infinite.

      If you have a finite amount of memory, say, n bits, then there is a finite number of states the memory can be in (2^n).

      No matter what the architecture of the processor, you can generalize it as something which reads the current state of memory, and other inputs, and produces a new state of memory (and possibly output).

      Ignoring for a moment the infinite possibilities one gets with peripheral input, we address your example, that of a fractal. Given that this should take place entirely in memory, we can safely ignore input. If you have finite memory, there are only a finite number of states the memory can be in. furthermore, because we are ignoring user input, and are using a deterministic processor, any given state of memory will always lead to a certain next state of memory.

      As a process runs, it will either
      a) halt
      or
      b) visit a state it has already visited.

      Simple proof: you have a state machine with n possible states. (in a binary computer with finite memory of m bits, 2^m = n). iterate it n+1 times.
      If it hasn't halted within this time, it MUST have visited one state more than once (pigeonhole principle).

      Cantor's argument is counterintutive, but true, as are the conclusions drawn about computability and the halting problem. The thing to realize, though, is that they apply to infinite sets.

      In finite sets, brute force trumps.

      --
      It's not stupid. It's Advanced.
    151. Re:No - there are plenty of safer alternatives by TemporalBeing · · Score: 1

      You still face the problem of receiving the data over the network and parsing the header first using unknown buffer sizes...so no, while that may help at the application/XML layer, it does not solve the problem across the spectrum...

      --
      Truth is like the sun. You can shut it out for a time, but it ain't goin' away. - Elvis Presley (source: imdb.com)
    152. Re:No - there are plenty of safer alternatives by Mauvaisours · · Score: 1

      Which makes the whole ban thing even more stupid as it will impact performance as well as security.

    153. Re:No - there are plenty of safer alternatives by lgw · · Score: 1

      Why should the comparison of source and destination sizes be done *in* memcpy? Any good code is going to compare what needs to be compared *before* memcpy (as well as validating pointers are non-NULL, etc) making this all a bit redundant and annoying.

      Sadly, I gave up on these library calls completely over disputes like this, and just write the code directly.

      --
      Socialism: a lie told by totalitarians and believed by fools.
  2. Should have been done 30 years ago. by Animats · · Score: 2, Insightful

    This should have been done thirty years ago.

    1. Re:Should have been done 30 years ago. by james_shoemaker · · Score: 4, Insightful

      Why? I can see some justification on the strXXX functions where you don't know how many bytes are going to be copied unless you call strlen first, but in memcpy you pass how many bytes to copy in as a parameter. So this is to protect programmers who can't do math?

    2. Re:Should have been done 30 years ago. by Shin-LaC · · Score: 1

      Maybe what should have been done was to standardize a "buffer" data type consisting of a pointer and a size. Then they could have guaranteed that a buffer's size is always passed along with its base pointer. When you only want to refer to part of a buffer, you would use a function (or even an operator, if they made "buffer" a primitive type) that alters the base pointer and/or the size appropriately. It would have been both safer and syntactically more convenient in many cases.

    3. Re:Should have been done 30 years ago. by darkwing_bmf · · Score: 3, Interesting

      If you haven't tried Ada yet, I highly suggest looking into it. It keeps track of data sizes, types, etc... for the programmer but it will also let you get close to the hardware like C does. It's often used for safety critical software such as that used in aviation.

      Unfortunately I can't recommend using Ada to develop windows apps. It's technically possible but you end up importing C library functions to do it. And if you're going to do that, you might as well just use a native development environment that is better suited to the task.

    4. Re:Should have been done 30 years ago. by jopsen · · Score: 1

      I agree, I don't see what you'd gain from removing it... Anybody why would care to explain...

      I understand that maybe it easier to make bugs when you pointers from one arbitrary type to another... And ignore the type system, (I have a habit of doing so, once in a while)... But wouldn't it be better to just no use C instead?

      Besides what the difference between memcpy and strncpy? or a simple for loop for that matter...

    5. Re:Should have been done 30 years ago. by Anonymous Coward · · Score: 0

      Most aviation apps are written in c and c++ nowadays. Ada is dying everywhere. Of course there will always be holdouts if you like doing legacy related stuff.

    6. Re:Should have been done 30 years ago. by darkwing_bmf · · Score: 1

      I've used all 3 languages and I speak from experience. Ada is better than C and C++ for system and safety critical applications. Even if one never plans to use it for development, Ada is still worth learning for a deeper understanding of what is possible in language and compiler design.

  3. malloc() and free() by Anonymous Coward · · Score: 5, Funny

    Those are also dangerous functions. And also array indexing! That should also be eliminated.

    1. Re:malloc() and free() by plague3106 · · Score: 2, Insightful

      Well there's a reason Java and C# have GCs to free you from having to worry about calling malloc and free..

    2. Re:malloc() and free() by Anonymous Coward · · Score: 1, Funny

      The more they make C++ "safe", the more it becomes like Java. The more they make Java "powerful", the more it becomes like C++.

      If you fix everything that is "wrong" in Java, you get C++. If you fix everything that is "wrong" in C++, you get Java.

      Funny how that works. It's as if one tool cannot be everything to everyone.

    3. Re:malloc() and free() by Anonymous Coward · · Score: 0

      Those are also dangerous functions. And also array indexing! That should also be eliminated.

      You joke, but there are two levels of programmers that I work with. One group can do whatever they want and not break the code. They know what they are doing.

      The other group is very good at translating requirements to interface with external hardware (DAQ, V/Is, Motor Control), but will hang themselves with very small amounts of rope.

      Granted, the parent post is talking about system software.

    4. Re:malloc() and free() by Joce640k · · Score: 1

      You don't call malloc/free in C++ either. What's your point?

      --
      No sig today...
    5. Re:malloc() and free() by Pseudonym · · Score: 1

      You jest, but I'm pretty much convinced that most good Java programmers use Java despite the language, rather than because of it. The real value in Java isn't the language, but the environment (VM, libraries etc).

      --
      sub f{($f)=@_;print"$f(q{$f});";}f(q{sub f{($f)=@_;print"$f(q{$f});";}f});
    6. Re:malloc() and free() by plague3106 · · Score: 1

      No, you need to call delete instead. Not much of an improvement.

  4. Python is done by sunami · · Score: 3, Funny

    Figures, Microsoft had to go kill of python and do it all in the name of security. No more accessing MEMory in C structures from our .PY files, damn it this really pisses me off.

    1. Re:Python is done by Rycross · · Score: 4, Informative

      No its not. This is only banned under Microsoft's Security Development Lifecycle, which means you only care about this if you're following those set of development guidelines. Its still in the language. And you can always use memcopy_s:

      Developers who want to be SDL compliant will instead have to replace memcpy() functions with memcpy_s, a newer command that takes an additional parameter delineating the size of the destination buffer.

    2. Re:Python is done by Anonymous Coward · · Score: 0

      I think you missed a joke there. Go back and read more carefully.

    3. Re:Python is done by Anonymous Coward · · Score: 0

      No way, they will live on in our hearts via Holy Grail DVD sales and Flying Circus reruns forever!

    4. Re:Python is done by powerlord · · Score: 1

      No its not. This is only banned under Microsoft's Security Development Lifecycle, which means you only care about this if you're following those set of development guidelines. Its still in the language. And you can always use memcopy_s:

      Developers who want to be SDL compliant will instead have to replace memcpy() functions with memcpy_s, a newer command that takes an additional parameter delineating the size of the destination buffer.

      Cool! So MS is now supporting cross-platform gaming? NEAT! ~

      (http://en.wikipedia.org/wiki/Simple_DirectMedia_Layer)

      I know its paranoia, but part of me keeps wondering if MS isn't just trying to redefine the SDL TLA.

      --
      This space for rent. All reasonable inquiries will be entertained at proprietors discretion.
    5. Re:Python is done by Anonymous Coward · · Score: 0

      What does memcpy_s actually do? Is it any more sophisticated than:

      #define memcpy_s(s,d,ss,ds) memcpy((s),(d),MIN((ss),(ds)))

    6. Re:Python is done by skeeto · · Score: 1

      Whoooosh!

    7. Re:Python is done by Anonymous Coward · · Score: 0

      whoosh?

  5. A half-measure, at best... by Smidge207 · · Score: 1, Insightful

    AFAIK memcpy() is only one of the many ways in which you can hang any half-awake coder himself in C (some manage it when awake, but let's say charitable - I'm ignoring the chorus asking "why?").

    Well done for thinking about security, boohoo for going straight to the press and trying to milk it instead of bloody DOING something for a change. Trust comes from casual "oh that? Yeah, we thought that was unsafe so we improved it" instead of trumpeting high and wide "look everyone, we bought a new padlock. Look how shiny it is, and how big" whilst still having a wooden backdoor with a simple latch only.

    Do, don't talk. Show me. We've 20 years of marketing so pardon me for being cynical.

    =Smidge=

    --
    Is it just my observation, or is eldavojohn an idiot?
    1. Re:A half-measure, at best... by wampus · · Score: 3, Funny

      So, Ben... or is it Peter? Do you always copy your comments verbatim from the linked article, or only when you agree with them?

    2. Re:A half-measure, at best... by Anonymous Coward · · Score: 0

      Nice catch. I never did like Smidge.

    3. Re:A half-measure, at best... by kjart · · Score: 1

      Blog post = trumpeting high and wide?

    4. Re:A half-measure, at best... by Lonewolf666 · · Score: 1

      I agree. Don't have that much experience with C, but even so I can immediately name a few things that might have "interesting" results:
      -Messing up pointer arithmetics
      -Buffer overflows from miscalculating array indices (not so different from pointer arithmetics)
      -Introducing unwanted compiler directives through a careless #include. Oh, there was a #pragma in that included file and now you get weird side effects? ;-)

      Bottom line:
      If reliability is more important than maximum performance and flexibility, don't use C in the first place. Some people call it a "high level assembler" for a reason.

      --
      C - the footgun of programming languages
    5. Re:A half-measure, at best... by gbjbaanb · · Score: 1

      If reliability is more important than maximum performance and flexibility, don't use C in the first place.

      Yeah, its *much* easier to make unreliable programs in higher level languages, especially the ones designed for the "enterprise".

    6. Re:A half-measure, at best... by shutdown+-p+now · · Score: 1

      This thing is intended as a simple safety guard for people who are specifically using C, and dealing with existing C code that uses standard functions such as strcpy and memcpy heavily.

      People who use C++ on Microsoft should just use std::string and std::vector, and checked iterators & algorithms. And then, of course, there's .NET, where you don't have to deal with such problems at all - so there's your "full measure".

      But, for the C scenario specifically, can you propose anything better?

    7. Re:A half-measure, at best... by ebuck · · Score: 1

      Please explain to me how I can walk off the end of an array in Java? I'm all ears.

    8. Re:A half-measure, at best... by Zancarius · · Score: 1

      So, Ben... or is it Peter? Do you always copy your comments verbatim from the linked article, or only when you agree with them?

      Very nice catch!

      See kids, this is why plagiarism isn't such a good thing. Someone, somewhere, will eventually catch you.

      For those who are curious or have no idea what wampus is referring to, both of these comments look painfully familiar.

      --
      He who has no .plan has small finger. ~ Confucius on UNIX
    9. Re:A half-measure, at best... by gbjbaanb · · Score: 1

      buffer overflows are not the only source of crap programs.

  6. good by Anonymous Coward · · Score: 0

    good

  7. No mention of memmove... by pthisis · · Score: 5, Informative

    Do you find this having a negative impact on the flexibility of the language, and do you think it will restrict the creativity of the programmer?"

    You can replace memcpy entirely with memmove (the latter is slightly slower and handles overlaps), and nothing in the article suggests that memmove is banned.

    But, no, it shouldn't hurt creativity--they're introducing a memcpy_s, which is the same aside from taking a size parameter for the destination. That's something that is generally easy to track in new code (obviously this secure developement lifecycle is not backwards compatible).

    --
    rage, rage against the dying of the light
    1. Re:No mention of memmove... by ifdef · · Score: 2, Insightful

      Okay, I'm obviously missing something here. How is having an extra parameter for the destination size any safer? I always thought the third parameter to memcpy was the amount of data to copy, and since obviously it should never be set to anything larger than the size of the destination, how will having the destination size explicitly passed in help any?

      Or are we just talking about a convenience feature that will make it easier for lazy programmers?

    2. Re:No mention of memmove... by ksheff · · Score: 2, Insightful
      big deal. Now developers will write

      memcpy_s(dst, sizeof(dst), src, sizeof(dst));

      instead of

      memcpy(dst, src, sizeof(dst));

      If they've been screwing up and using the wrong size for the number of bytes to copy, what's going to stop them from screwing up and putting the wrong size for the size of the destination buffer? Nothing! Now the coders that have been using something like

      MIN(sizeof(dst), bytes_to_copy)

      for the last parameter for years will have to change their code. Oh well...it's job security for someone.

      --
      the good ground has been paved over by suicidal maniacs
    3. Re:No mention of memmove... by gowen · · Score: 1

      which is the same aside from taking a size parameter for the destination.

      So Microsoft has invented the wrapper:

      memcpy_s(void*dest,const void*src, size_t dest_num, size_t src_num)

      is basically the same as

      if(dest_num > src_num) {
            throw std::logic_error("You're incompetent");
      }else {
            memcpy(void*dest,const void*src, src_num);
      }

      except its exception mechanism isn't the standard one. (And its not MS Structured Exceptions either, its something else completely new). Now I know they need to claim its a C thing too (memcpy isn't as useful in C++, as the standard doesn't guarantee you can copy non-POD objects with it), but every that wrapper function serves no real purpose. Seriously. If you're code is so labyrinthine that you can't keep track of your buffer sizes, you've got worse problems than memcpy().

      --
      Athletic Scholarships to universities make as much sense as academic scholarships to sports teams.
    4. Re:No mention of memmove... by pthisis · · Score: 3, Informative

      Okay, I'm obviously missing something here. How is having an extra parameter for the destination size any safer? I always thought the third parameter to memcpy was the amount of data to copy, and since obviously it should never be set to anything larger than the size of the destination, how will having the destination size explicitly passed in help any?

      That's the error that this is trying to fix. I'm skeptical as to how much this will help; if you're that lazy, you can just set the destination size parameter to the same value as the amount to copy.

      But it might be easier to enforce at a code-review level in the organization: destination size always has to be a size tracked based on memory allocation.

      --
      rage, rage against the dying of the light
    5. Re:No mention of memmove... by pthisis · · Score: 3, Informative

      Now developers will write

              memcpy_s(dst, sizeof(dst), src, sizeof(dst));

      I get the feeling that this is mainly for Microsoft internally developed code which conforms to their security guidelines. As such, it's probably mainly intended to help in code reviews. Still pretty dubious.

      Now the coders that have been using something like

              MIN(sizeof(dst), bytes_to_copy)

      for the last parameter for years will have to change their code.

      That fails in the common case of dst being a real pointer (whether it's indexing into a static array or dynamically allocated memory or whatever).

      --
      rage, rage against the dying of the light
    6. Re:No mention of memmove... by KumquatOfSolace · · Score: 1

      I see the motivation (prevent buffer overflow exploit when programmer lazily uses a fixed-size buffer and doesn't check if the data is too big). But it will probably actually CAUSE bugs. More parameters = more confusion, more risk of mixing the parameters up and getting them wrong. The new parameter (destination size) does not add any functionality, yet if you get it wrong it will break your code. I guess the hope is that those bugs will be caught by QA, whereas buffer overflows might not (because overflow won't occur during normal use).

      Documentation for memcpy_s is rather confusing (naming of parameters is weird) increasing risk that a novice programmer will mess things up.

    7. Re:No mention of memmove... by 91degrees · · Score: 1

      (the latter is slightly slower and handles overlaps)

      Considering the trivial overhead of testing for overlap I'm surprised we still have memcpy.

    8. Re:No mention of memmove... by Intron · · Score: 1

      #define COPYBUFFER(dst, src, len) memcpy_s(dst, sizeof(dst), src, len)

      --
      Intron: the portion of DNA which expresses nothing useful.
    9. Re:No mention of memmove... by Anonymous Coward · · Score: 0

      #define memcpy(dst, src, size) do { size_t s = (size); memcpy_s((dst), s, (src), s); } while (0)

      There all secure now.

    10. Re:No mention of memmove... by discord5 · · Score: 1

      But, no, it shouldn't hurt creativity--they're introducing a memcpy_s, which is the same aside from taking a size parameter for the destination.

      Well, that and you can still use it if you really want to, which is what a lot of C programmers will be doing regardlessly.

    11. Re:No mention of memmove... by dzfoo · · Score: 1

      >> Okay, I'm obviously missing something here. How is having an extra parameter for the destination size any safer?

      That extra parameter represents the "are you really sure?" confirmation from the developer.

            -dZ.

      --
      Carol vs. Ghost
      ...Can you save Christmas?
    12. Re:No mention of memmove... by Tony+Hoyle · · Score: 2, Informative

      Given that dst is a pointer, sizeof(dst) is generally going to be 4 or 8, and not do what you want.

      It's more likely that programmers will just pass len to both parameters, defeating the point. Unless you define a pointer type that contains a length attribute (which wouldn't be a bad idea, but MS haven't done that) you're just relying on lengths being passed around the code being accurate, which isn't any safer.

      A bad programmer will always be a bad programmer. Someone who would use strcpy on user data or memcpy not knowing the destination length, is the same kind of person that's going to work around this. For everyone else it's just a pain.

    13. Re:No mention of memmove... by Tony+Hoyle · · Score: 2, Informative

      memcpy_s(dst, sizeof(dst), src, sizeof(dst));

      Whilst that will work, it probably doesn't do what you think.

      Hint: dst and src are pointers.

    14. Re:No mention of memmove... by Megane · · Score: 1

      #define memcpy_s(dest,destlen,src,srclen) { assert(destlen <= srclen); memcpy(dest,src,srclen); }

      Really, that's all it sounds like this is, along with forbidding memcpy used other than this way. Belt and suspenders.

      And nobody is forcing you to do this unless your employer's name happens to be "Microsoft".

      --
      #naabhaprzrag, #sverubfr-000, #agi-fcbafberq, negvpyr[pynff*=' negvpyr-ary-'] { qvfcynl: abar !vzcbegnag; }
    15. Re:No mention of memmove... by Megane · · Score: 1

      You do know that dst is a pointer type, so sizeof(dst) is always equal to 4? (or 8 in 64-bit)

      --
      #naabhaprzrag, #sverubfr-000, #agi-fcbafberq, negvpyr[pynff*=' negvpyr-ary-'] { qvfcynl: abar !vzcbegnag; }
    16. Re:No mention of memmove... by Anonymous Coward · · Score: 0

      Or if like in most companies that warnings get treated like errors you then have to tediously change all your code to use this new, nonportable microsoft extension.

    17. Re:No mention of memmove... by Intron · · Score: 1

      Pointers have size 4 or 8, but buffers are typically an array type, like char[80].
      That's why the macro is named COPYBUFFER and not COPYMEM.

      Obviously, once you use a pointer, you can stick anything in the dest size and have no way to check.

      --
      Intron: the portion of DNA which expresses nothing useful.
    18. Re:No mention of memmove... by JorgeFierro · · Score: 1

      Not if they are arrays and they were not passed as a function argument:

      char buffer[10];
      sizeof buffer = 10

    19. Re:No mention of memmove... by EkriirkE · · Score: 1

      Then, on the flipside, your macro is using direct, not pointers for the dest/src arguments...

      --
      from 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0
      to 45 2F 6E 40 3C DF 10 71 4E 41 DF AA 25 7D 31 3F
    20. Re:No mention of memmove... by weicco · · Score: 1

      That's the error that this is trying to fix. I'm skeptical as to how much this will help

      I think the idea is that memcpy_s forces, or tries to force, coder to think. Is destination buffer really long enough? Should I check it's length somehow? But I'm a little skeptical too. Good coders don't need functions like memcpy_s anyway and lazy-ass coders cut the corners and make their own memcpy #defines.

      --
      You don't know what you don't know.
    21. Re:No mention of memmove... by sl149q · · Score: 1

      memcpy_s() also returns an errno_t, so you would now use something like: if ((memcpy_s(dst, dstsize, src, bytes) { // check errno for reason copy failed }

    22. Re:No mention of memmove... by petermgreen · · Score: 1

      It's more likely that programmers will just pass len to both parameters, defeating the point
      Which should be slapped down in code review.

      As I see it the point of theese functions is to introduce a layer of sanity checking that is relatively independent of the main data/control flow and hence much easier to check correctness of come code review time.

      --
      note: i'm known as plugwash most places but i screwd up registering that here somehow in the past and now can't register
    23. Re:No mention of memmove... by ksheff · · Score: 1

      Whilst that will work, it probably doesn't do what you think. Hint: dst and src are pointers.

      It does exactly what I think it does if they are arrays, but that's not the point. Adding another parameter isn't going to make code that much safer if you're going to rely on the same programmers to "do the right thing" in memcpy_s() when they couldn't be relied on do something safe with the existing function. The only thing this buys you is that it now returns an error if you try to copy too much, which will probably be ignored. But, yes, doing sizeof() for a variable that is a pointer isn't going to return what many newbie programmers want it to do: return the size of the thing at that address.

      --
      the good ground has been paved over by suicidal maniacs
    24. Re:No mention of memmove... by JorgeFierro · · Score: 1

      Keith?

    25. Re:No mention of memmove... by prockcore · · Score: 1

      Actually, memmove is banned. It has been replaced with memmove_s.

    26. Re:No mention of memmove... by setagllib · · Score: 1

      If you're [sic] code is so labyrinthine that you can't keep track of your buffer sizes, you've got worse problems than memcpy().

      That's exactly why this originated in Microsoft and not in GNU, BSD or Linux. People who can distinguish their ass from a pointer are fine with memcpy.

      --
      Sam ty sig.
    27. Re:No mention of memmove... by setagllib · · Score: 1

      I'd rather keep memcpy and drop memmove. But because the standard requires memcpy to work in a specific way even with overlap, it would now break backwards compatibility (for very few programs..) to add that hack to memcpy.

      --
      Sam ty sig.
    28. Re:No mention of memmove... by Haeleth · · Score: 1

      big deal. Now developers will write

      memcpy_s(dst, sizeof(dst), src, sizeof(dst));

      No, they'll just write

      #ifdef WIN32
      #define memcpy(a,b,c) memcpy_s(a,c,b,c)
      #endif

      and get on with their lives. And all will be well right up until the "c" parameter turns out to include a side effect, at which point all hell will break loose.

      Really, Microsoft should know better. If you try to make your API foolproof, someone will just invent a better fool.

  8. The truth of this is ... by Anonymous Coward · · Score: 0

    A corporate-level "improvement" officer at Microsoft asked: What part of our operating system is the source of slow downs in our applications and partner applications?

    A profile of code showed that memcpy() was taking the most CPU time. Instead of asking why memcpy was being called so much and suggesting removal of unneeded memcpy calls, they decided that nobody should use memcpy because it has the possibility of being used incorrectly when their own programmers don't know how to determine the proper size of data structures.

  9. They should go one better... by Smidge207 · · Score: 5, Insightful

    ...and pop up a message box asking the user to confirm they want to copy the memory, and if they press OK then they should have to enter a captcha.

    Seriously though, how is it supposed to make your code safer if you pass the size you think your destination buffer is? With memcpy, that size is implicitly greater or equal to the copy size and it's the caller's responsibility to make sure this is the case. Putting bounds checking into the copy function is ridiculous if you're responsible for passing the bounds yourself, and it goes against basic good design. I'm surprised they aren't passing the source buffer size too, just to be extra safe. Also, what happened to the __restrict keyword? It's strangely absent from the memcpy_s function declaration.

    =Smidge=

    --
    Is it just my observation, or is eldavojohn an idiot?
    1. Re:They should go one better... by Anonymous Coward · · Score: 0

      I see you read the article, too.

    2. Re:They should go one better... by Creepy · · Score: 4, Informative

      The problem is memcpy returns a void *. If this is dynamically cast, it needs to be checked at runtime and may even be set to a value the programmer never intended (say unsigned 16 bit values instead of unsigned 8 bit characters). It may be an issue with updating the code - say the code was originally written for 8 bit ASCII and got updated to, say UTF-16 (16 bit). A dynamically cast void* doesn't care what the size is, it just shoves the values in the buffer. This may work fine in basic testing even, because you never overflow the buffer with 1-2 characters, and maybe even gets past a QA team, but once you go past 1/2, you've got a buffer overrun.

      As I understand it, __restrict wouldn't work in a C++ program using dynamic_cast because it doesn't know the size at compile time (sorry, I'm not sure what is done in C as I haven't kept up with the language, so I have to use a C++ example). My guess is memcpy_s does runtime bounds checking (it isn't specified on the memcpy_s page, maybe the security ref - too busy to read it though).

    3. Re:They should go one better... by shutdown+-p+now · · Score: 1

      Seriously though, how is it supposed to make your code safer if you pass the size you think your destination buffer is?

      Quite often when using memcpy you actually do know the size of your destination buffer - it's sizeof(buffer), when it's an array.

      On the other hand, it's fairly easy to forget that the buffer is actually of limited size, which may be less than the size of the data you're copying over. This is supposed to catch these kinds of things, nothing more.

      Also, what happened to the __restrict keyword?

      And what should happen to it? There is no such thing in the C++ standard, and MSVC is a C89 & C++03 implementation. It's definitely not a C99 implementation, and that isn't even claimed (I don't think it even implements a single C99 feature apart from // comments - it won't even let you put variable declarations between statements in .c files).

      By the way, all those safe *_s functions actually come from an ISO TR for C99 - here is the PDF of the spec. Now that thing is specifically for C99, so it has "restrict" in all the proper places.

    4. Re:They should go one better... by Prof.Phreak · · Score: 2, Informative

      Eh? the 'n' in memcpy call is number of -bytes-. not "things" you're trying to copy. it doesn't matter if you give it an array of signed 8 bit characters and copy it over to 32bit unsigned longs... you just specify n to be number of -bytes- to copy.

      How can this be confusing?

      --

      "If anything can go wrong, it will." - Murphy

    5. Re:They should go one better... by TheLink · · Score: 1

      > how is it supposed to make your code safer if you pass the size you think your destination buffer is?

      When there's more than one coder working on a project, some other coder might have a different idea of what the destination buffer is supposed to be, or change it.

      If that happens people can still play the blame game whether it's memcpy or some safer function. But if the resulting code allows "an attacker to execute arbitrary code of his choice" then it's a pretty crappy standard function, and a stupid primitive way of doing things.

      It's stupid to design all cars to blow up on crashes just so that people end up being safer drivers. It makes cars a lot less useful as a mode of transport.

      Crappy standard (or de-facto standard) functions make a computer language less useful as a way of telling a computer what to do.

      --
    6. Re:They should go one better... by adisakp · · Score: 1

      Seriously though, how is it supposed to make your code safer if you pass the size you think your destination buffer is?

      The safe versions use templates to automatically determine the size of destination buffers for arrays that are not pointers. This solves the problem automatically for a large number of cases.

      Also, what happened to the __restrict keyword? It's strangely absent from the memcpy_s function declaration.

      There is no need to pollute your interface with __restrict in the function declaration. Even if __restrict is not in the function declaration, it's possible to simply copy the pointer to a __restrict pointer in the function body itself and the compiler can generate equally optimized code in the function. FWIW, __restrict won't actually prevent you from passing in overlapping buffers (with unpredictable results) so putting it there would at most give you a false sense of security.

    7. Re:They should go one better... by X3J11 · · Score: 1

      I'd mod you up, had I the points. How the GP scored an informative, I'm not sure. Oh wait, yes I am. This is Slashdot, where it's expected to spread incorrect information which could have easily been verified before hitting that Submit button.

      NAME
      6.8 `memcpy'--copy memory regions
      SYNOPSIS
      #include string.h
      void* memcpy(void *OUT, const void *IN, size_t N);
      DESCRIPTION
      This function copies N bytes from the memory region pointed to by IN to the memory region pointed to by OUT.
      If the regions overlap, the behavior is undefined.
      RETURNS
      `memcpy' returns a pointer to the first byte of the OUT region.

    8. Re:They should go one better... by Malc · · Score: 1

      My guess is memcpy_s does runtime bounds checking (it isn't specified on the memcpy_s page, maybe the security ref - too busy to read it though).

      If you have VS.Net and the CRT source installed, you can easily check this.

      Yes, it does some range checking and pointer checks, memset'ing of the dest if the source is NULL or the dest is smaller. Then delegates to memcpy. Memcpy does no checking whatsoever.

    9. Re:They should go one better... by BrianRoach · · Score: 1

      Um ... huh?

      It returns a (void) pointer to the same memory address as the destination you passed in. It's really not all that useful and you can just ignore it.

      memcpy() doesn't care what the memory contains or what it represents. It simply copies n bytes from one place to another.

      If you don't know what your data is, or how long the memory segment you malloc'd is ... um, you've got other problems.

  10. Isn't security the programmer's responsibility? by Mhtsos · · Score: 0, Troll

    I can understand the warning "Warning: you are using an Evil Command(R) "memcopy" and your program will be a piece of crap as a result", but there's no need to break already compiling code.
    (FP btw)

    1. Re:Isn't security the programmer's responsibility? by Anonymous Coward · · Score: 5, Informative

      you didnt read.

      MSFT is banning it from their development process, not the language, use it as much as you like.

    2. Re:Isn't security the programmer's responsibility? by pdbaby · · Score: 1

      there's no need to break already compiling code

      That compiling code is the problem - it could potentially be exploited (and the software can't really analyse your binaries to determine if you're being safe and checking everything properly)

      --
      Global symbol "$deity" requires explicit package name at line 2. - If only $scripture started "use strict;"
    3. Re:Isn't security the programmer's responsibility? by Mhtsos · · Score: 1

      you're right, my bad

    4. Re:Isn't security the programmer's responsibility? by Anonymous Coward · · Score: 1, Insightful

      >Isn't security the programmer's responsibility?
      You must be kidding. The average code monkey has failed miserably at that responsibility, time after time, for decades.

      >(FP btw)
      Fail.

    5. Re:Isn't security the programmer's responsibility? by GeckoFood · · Score: 1

      Security used to be the programmer's responsibility, yes. The shift in language design has been to move the responsibility from the coder to the language. When you have an enforcing language doing the checking, the theory is that it reduces costs in the maintenance phase.

      Ada is a prime example of this. To get code to even compile is a real chore, but once you have it compiling there's a strong chance that it will be relatively free of careless errors that would drive up costs when in maintenance. It doesn't fix logic errors, of course, but it makes it a lot harder to have memory errors and conversion issues.

      Java also does some of this through the JVM. The Java developer cannot *directly* manipulate pointers, as the language designer[s] decided that free access to memory was too risky and was the cause of a lot of strangeness at runtime. Also, it enforces conversion checking and even exception definitions.

      Little by little, the responsibility of security is being taken away from developers.

      --
      Be excellent to each other. And... PARTY ON, DUDES!
    6. Re:Isn't security the programmer's responsibility? by petermgreen · · Score: 1

      and even exception definitions.
      Only very weakly.

      Firstly your code can always throw any descendent of error or runtimeexception regardless of it's declared throws. How many times have you seen something like.


      try {
          some code
      } catch (someexception e) {
          throw new RuntimeException(e);
      }

      still I guess it's better than

      try {
          some code
      } catch (someexception e) { }

      P.S, there is actually a way mentioned in suns own documentation to throw any exception you wish regardless of your throws specifier.

      --
      note: i'm known as plugwash most places but i screwd up registering that here somehow in the past and now can't register
  11. First they take my gets.. by adonoman · · Score: 5, Funny

    First they came for gets, then they took scanf and strcpy, now they want memcpy? Outrageous! How are virus writers going to be able to take advantage of buffer overflows if I'm continuously keeping track of how big my buffers are? I may have to start lying about their size just to give hackers a chance.

    1. Re:First they take my gets.. by Anonymous Coward · · Score: 5, Funny

      First they came for gets, And I didn't speak up because I didn't use gets
      Then they came for scanf, And I didn't speak up because I didn't use scanf
      Then they came for strcpy, And I didn't speak up because I didn't use strcpy
      And then... they came for memcpy... And by that time there was no one left to speak up.

    2. Re:First they take my gets.. by wisty · · Score: 1

      Just wait till they realize what a security hole database queries are!

    3. Re:First they take my gets.. by An+ominous+Cow+art · · Score: 1

      Won't someone please think of the script kiddiez?

  12. What an idiotic idea. by Anonymous Coward · · Score: 5, Informative

    Someone already explained this better than I could.

    1. Re:What an idiotic idea. by Anonymous Coward · · Score: 0

      Or you can use a general purpose language and be done with it.

    2. Re:What an idiotic idea. by EvanED · · Score: 1

      That article is poorly written and poorly thought out.

      If one length parameter is insufficient to prevent muppets from screwing up, what makes you think that adding more of the same is going to have any real effect.

      There are two arrays to overflow, so passing in one length parameter requires (in the general case) taking the min first. In other words, this change turns 'memcpy(buf1, min(size1, size2), buf2)' into 'memcpy_s(buf1, size1, buf2, size2)'. Slightly simpler (IMO).

      The more important step is that it will encourage programmers to actually attempt to track both size1 and size2. With memcpy, you have to go the extra mile to be safe because you have to actually include the call to min instead of just passing one of the parameters -- in other words, it's easier to be unsafe than it is to be safe. With memcpy_s, if you have both length parameters around, it's as easy to pass both as it is to not. If you don't, you have to make something up -- and just about every "something" I can think of will stand out pretty strongly as a sore thumb.

    3. Re:What an idiotic idea. by Anonymous Coward · · Score: 0

      Sorry, but I'd rather trust the guy who is one of the main Perl core hackers out there, responsible for the excellent perl security track record (1 vulnerability in two years on average) than random guys over the internet or Microsoft.

    4. Re:What an idiotic idea. by residieu · · Score: 2, Insightful

      taking the min is probably not what you want to do. If you don't have room in the destination for everything you want to copy, you need to find a new destination. Copying just part of the source memory is going to lead to strange behavior down the road (when you start interpretting the copied memory and it cuts off suddenly). So this just changes checking the sizes before the memcpy call and handling the error there into check the error code from memcpy_s, and handling the error afterwards.

    5. Re:What an idiotic idea. by maxwell+demon · · Score: 1

      There are two arrays to overflow

      Well, that's an argument to have three size parameters: One for the size of the source array, one for the size of the destination array, and one for the amount to copy. After all, the amount to copy not just shouldn't exceed the destination array size, but also shouldn't exceed the source array size. So according to this argument, the perfect function would be

      void memcpy_ss(void* dest, size_t destsize, void* src, size_t srcsize, size_t size)

      with an error if size exceeds either srcsize or destsize.

      --
      The Tao of math: The numbers you can count are not the real numbers.
    6. Re:What an idiotic idea. by ClosedSource · · Score: 1

      Don't trust, verify.

    7. Re:What an idiotic idea. by iluvcapra · · Score: 2, Informative

      The more important step is that it will encourage programmers to actually attempt to track both size1 and size2.

      I think you misunderstand his point... the 'size' parameter isn't the number of bytes in either buffer, it's the number of bytes you want to move. Obviously this has a lot to do with the size of either allocated buffer, but it's not the same thing.

      memcpy doesn't know what a buffer is-- no, it really doesn't. At it's heart, all it does is copy a byte from one pointer to another and increment both, until it's done 'size' of them. There's no requirement that the pointers passed to memcpy be pointers to arrays. They just have to be pointers.

      The idea that 'size' actually corresponds to the number of allocated elements in an array is a leaky abstraction. Obviously you never want to copy more bytes than either buffer has the capacity for, but that's really not the language's responsibility to enforce, because the language has no first-class concept of a "buffer" of known length. By making the function 'safer,' all they're doing is encouraging the leaky abstraction and confusing people who think memcpy's job is to copy "buffers" when all it really does is copy n bytes. These developers who have written memcpy_s may have made it "safer," but at the expense of giving it another error condition that must be tested for, and making the actual workings of the function more obscure.

      Let's say, If I only want to copy the first 3 bytes of src to dest, do I put in "3" for the source length or the destination length? And I'd better test that against the length of both first, because if the function fails, was it because there's only 2 bytes available in dest, or because there's only 2 available in src? OR, if I'm starting at byte 2 of src to dest, do I put "1" in for srcLength, because that's alll that's left in the array, or "3," because that's how big the array is? I know it probably should be the first one, but the people who don't know better, the people this function is theoretically trying to engineer against, probably will make the wrong choice, because they have it in their head the array is length "3" and this function wants to know the length of the array, right?

      --
      Don't blame me, I voted for Baltar.
    8. Re:What an idiotic idea. by RightSaidFred99 · · Score: 1

      Yeah, because Microsoft hires idiots for programmers. Joe Bloe "from the internet" is probably a more experienced, educated, and better developer.

      I love your reality distortion field, you hate Microsoft ergo all their money couldn't possibly buy the best and brightest - they are instead all idiots.

    9. Re:What an idiotic idea. by EvanED · · Score: 1

      I'm not saying that the guy is wrong in his opinions, just that he expressed them incredibly poorly in that post.

      The argument basically boils down to "there's already a size argument, so why do you need another one", but completely ignores the somewhat obvious reason why having another one might actually be a good idea. It doesn't present any additional arguments, and it doesn't refute mine.

    10. Re:What an idiotic idea. by EvanED · · Score: 1

      This is a really good point, but I still think that dropping pure memcpy has benefits.

      In particular, what percentage of security bugs out there are caused by buffer overflows? I don't actually know, but it sure seems like a very large proportion. It seems reasonable to think that having a bug where you incorrectly overwrite memory (like what you have if you're using memcpy incorrectly) is much more likely to result in a security vulnerability than one where you stop copying partway through.

    11. Re:What an idiotic idea. by EvanED · · Score: 1

      This would definitely be somewhat reasonable, but I think that going from memcpy to memcpy_s gets you most of the benefit of your memcpy_s_s, for two reasons. First, it seems easier to maintain the invariant that the amount you're copying is smaller than the buffer its in then ensuring that the destination buffer is large enough, since the first two pieces of information (the size of the source buffer and the size of the data) are much more tightly coupled than the latter two pieces of information (the size of the data and the size of the destination buffer) often are.

      Second, it's very often the case that the size of the source buffer and the size of the data are actually the same -- more common I'd wager than the size of the data and size of the destination buffer are.

      I don't have a lot of development experience, but I do have some (including some kernel hacking). Forbidding use of memcpy seems like a good idea to me, but I'm not terribly confident in that. I'm much more confident that the article I was originally replying to makes an incredibly bad case for why it's not a good idea.

    12. Re:What an idiotic idea. by EvanED · · Score: 1

      I think you misunderstand his point... the 'size' parameter isn't the number of bytes in either buffer, it's the number of bytes you want to move. Obviously this has a lot to do with the size of either allocated buffer, but it's not the same thing.

      That's right, but that doesn't change my argument. In the general case, if you wanted to use memcpy in a manner I would consider secure, you still need the min in there with memcpy and not with memcpy_s. ...but that's really not the language's responsibility to enforce...

      We have a bit different ideas of what the language should do. And even if the language doesn't actually enforce that you don't run out of bounds (which even memcpy_s doesn't do), it can still make it easier to use correctly and harder to use incorrectly.

      My take is that memcpy_s probably does that, and I think that's a worthwhile step to take, especially when it's almost free.

      Let's say, If I only want to copy the first 3 bytes of src to dest, do I put in "3" for the source length or the destination length?

      I would say that depends on the motivation. If it's because you only want the first 3 bytes of src, it should go in the source length. If it's because the destination buffer is only 3 bytes, it goes into the dest size.

      (Of course, you'll probably do some testing before calling memcpy_s in the first place, because of what your sibling post said about there really being 3 sizes involved. To be completely defensive, you'll at least need to test it against whichever buffer size 3 replaces.)

      And I'd better test that against the length of both first, because if the function fails, was it because there's only 2 bytes available in dest, or because there's only 2 available in src?

      I would say that if you need to do those tests with memcpy_s, you need to do those tests before calling plain memcpy anyway, for almost any definition of "need".

      OR, if I'm starting at byte 2 of src to dest, do I put "1" in for srcLength, because that's alll that's left in the array, or "3," because that's how big the array is? I know it probably should be the first one, but the people who don't know better, the people this function is theoretically trying to engineer against, probably will make the wrong choice, because they have it in their head the array is length "3" and this function wants to know the length of the array, right?

      I can sort of see where you're coming from, in that the terminology we're using has shifted a little bit (from bytes-to-copy to sizes of buffers). However, I don't think this is that much of a greater issue than with plain memcpy. Also, the MS documentation for memcpy_s, while it uses a really crappy name for the second parameter, the name and description of the last one are about the same as for memcpy -- the number of bytes to copy. (It says "characters", but 1 char = 1 byte.)

    13. Re:What an idiotic idea. by mdwh2 · · Score: 1

      Personally I'd rather judge based on what people say, rather than one of them claiming he has some kind of authority because he writes on a blog.

      Oh, and:

      Sorry, but I'd rather trust the guy who is one of the main Perl core hackers out there, responsible for the excellent perl security track record (1 vulnerability in two years on average) than random guys over the internet or Microsoft. ...and random anonymous cowards posting on a forum. So no, I don't trust you.

    14. Re:What an idiotic idea. by Anonymous Coward · · Score: 0

      At expense of lower performance for the prevalent case of memcpying fixed size sections of memory to appropriately sized buffers. This is not as expensive as strncpy_s, but it is meaningless and un-C-ly.
      If you can't deal with that responsibility and are willing to write slow managed code, you should write your apps in C#. It is a hobby language that nobody uses, but I heard it was developed by a major company.

  13. Typical by tb3 · · Score: 1

    Lots of hand-waving marketing bullshit. I'm sure they're going to keep using it internally, and the exploits will still happen with Microsoft code. Just like Microsoft applications will be ignored by UAC in Windows 7.

    If they wanted to do something useful, they should have removed createRemoteThread instead.

    --

    www.lucernesys.comHorizon: Calendar-based personal finance

  14. #define memcpy memmove by the_arrow · · Score: 2, Insightful

    I have often used memcpy instead of strcpy when I have known the length of the strings, and also known the destination to be large enough.
    I'm guessing many developers will just #define memcpy to something else and continue as nothing happened.

    --
    / The Arrow
    "How lovely you are. So lovely in my straightjacket..." - Nny
    1. Re:#define memcpy memmove by descil · · Score: 1

      I'll just continue using gcc; nothing DID happen.

    2. Re:#define memcpy memmove by drew · · Score: 1

      or better:
          #define memcpy(x,y,z) memcpy_s(x,y,z,z)

      --
      If I don't put anything here, will anyone recognize me anymore?
    3. Re:#define memcpy memmove by SL+Baur · · Score: 1

      I have often used memcpy instead of strcpy when I have known the length of the strings, and also known the destination to be large enough.

      That's error prone. You have to either guarantee the destination is already zero byte filled, or be sure to copy the sentinel in the source string.

      As others have pointed out, if you want to do stuff (reasonably) securely and quickly, you should be using a language like Ada.

      My moment of enlightenment came when writing a string copy module in Modula 2. Modula 2 offered the brain damage of accepting both C-style NUL terminated strings and normal bounded arrays of characters.

    4. Re:#define memcpy memmove by ucblockhead · · Score: 1

      I gather you never deal with non-ASCII strings.

      --
      The cake is a pie
    5. Re:#define memcpy memmove by Anonymous Coward · · Score: 0

      You mean like this?

      #define memcpy_s(x, y, z, a) memcpy((x),(y),(z))

      Or like:

      #define memcpy(x, y, z) memcpy_s((x),(y),(z),-1)

      Or maybe:

      #define i_am_not_memcpy_rly(x, y, z) memcpy((x),(y),(z))

    6. Re:#define memcpy memmove by Anonymous Coward · · Score: 0

      The syntax is not like that, so you would get a compiler error.

      From AC below:

      #define memcpy(x, y, z) memcpy_s((x),(y),(z),-1)

      This is how C is supposed to be used.

    7. Re:#define memcpy memmove by the_arrow · · Score: 1

      That's error prone. You have to either guarantee the destination is already zero byte filled, or be sure to copy the sentinel in the source string.

      Of course. Using "length + 1" isn't that hard. Cut my teeth with this in the mid to late 90's, doing network buffering for muds. :)

      --
      / The Arrow
      "How lovely you are. So lovely in my straightjacket..." - Nny
    8. Re:#define memcpy memmove by the_arrow · · Score: 1

      Up until recently, I've only used 8-bit characters. Around a year now I have been working mostly with C#, which means I don't have to worry about character width or such stuff that much.
      Actually, despite its Microsoft origin, I think C# is actually quite nice language, with pretty good default class library. I'm even thinking about doing some private programming with it, using Mono on Linux.

      --
      / The Arrow
      "How lovely you are. So lovely in my straightjacket..." - Nny
    9. Re:#define memcpy memmove by ucblockhead · · Score: 1

      Just an FYI: If you ever deal with a non-ASCII encoding, like UTF-8, you can't rely on strings being exactly one byte per character. strcpy allows for that. memcpy doesn't.

      --
      The cake is a pie
  15. then why are you using C? by Anonymous Coward · · Score: 2, Insightful

    If you consider memcpy too dangerous then you should be using something besides C. If you're using C++ and memcpy then you really do need to know what both you and the compiler are doing.

    1. Re:then why are you using C? by tepples · · Score: 1

      If you're using C++ and memcpy then you really do need to know what both you and the compiler are doing.

      Yes, you should generally use operator = instead of memcpy, and new T(other_object) instead of malloc followed by memcpy, for objects that are or contain rule-of-three objects. Otherwise, objects' ownership of resources gets screwed up. But you can rely on C-like behavior when using memcpy or memcpy_s on C-like objects (commonly called Plain Old Data, or PODs).

    2. Re:then why are you using C? by jgrahn · · Score: 1

      If you're using C++ and memcpy then you really do need to know what both you and the compiler are doing.

      If you're using C++ and memcpy(), then you probably *don't* know what you're doing. You should just copy your objects using = (just like C users should, although many seem stuck in the 1970s and insist on memcpy()ing anything larger than 32 bits) or if it's sequences you're copying you should use std::copy which unlike memcpy() is type safe and works on anything which can be iterated over.

  16. The difference bewteen memcpy() and strcpy() by Anonymous Coward · · Score: 3, Insightful

    The problem with strcpy() and sprintf() and like functions is that you don't know when calling them the length of the source to be copied into the supplied buffer. But with memcpy() you specify this length.

    Frequently, the size of the target is calculated at run time, so bugs in memcpy() tend to be in the area of this calculation, rather than in not checking if the source fits the target.

    Any lack of memcpy() would be easy to overcome, just use

              memcpy_s (dst, len, src, len)

    which is functionally identical to

              memcpy (dst, src, len)

    1. Re:The difference bewteen memcpy() and strcpy() by rikkitikki · · Score: 1

      Either Microsoft is really stupid or really evil. Along with declaring printf(), et. al. "not portable, use _printf() instead", we should now use memcpy_s(). Let me go see where that is defined in the C standard. Oh, that's right, it isn't. It's only on Microsoft platforms.

      So, what's going on here? Make up your own function (not in the C standard) to replace memcpy() and tell people to use that rather than memmove() (which is in the C standard). What the hell is the motivation here?

    2. Re:The difference bewteen memcpy() and strcpy() by v1 · · Score: 1

      y'know if you'd just all use BASH none of this would be a problem.

      --
      I work for the Department of Redundancy Department.
    3. Re:The difference bewteen memcpy() and strcpy() by SL+Baur · · Score: 1

      Let me go see where that is defined in the C standard.

      ISO/IEC TR 24731-1:2007 - http://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=38841

    4. Re:The difference bewteen memcpy() and strcpy() by Anonymous Coward · · Score: 0

      The difference is that people using that method will be intentionally bypassing its intent, and probably will be making unsafe assumptions in any code that they write (or have written in the past)

      I suspect, though, that there will be at least someone that uses it as intended, if it is possible in their case, reducing the number of overflows due to a mistake. This is assuming they are able to track the size of memory allocated through the execution path from allocation to memcpy in their particular application.

      If that's true (and I suspect it is) then their attempt at reducing the problem has succeeded by at least one person (though I suspect it will be many many more).

      In my line of work I not only expect to see these mistakes, but I count on them to do what I need to do (yes, legally).

  17. Removal vs deprecation by GodfatherofSoul · · Score: 1

    I don't trust outright removals without a decent period of deprecation. Microsoft has a bad history of deciding some API or function is dirty and obsolete, only to find that they've broken some of their own code or made some functions impossible to implement in some environments.

    For example, they deprecated a Windows Mobile database API without having support for the new version in ActiveSync. Lots of suckers upgraded only to find out that the Grand Pubas down at Seattle Central pulled the rug out from under them.

    I worry very much about problems in eccentric environments like mobile or embedded development.

    --
    I swear to God...I swear to God! That is NOT how you treat your human!
    1. Re:Removal vs deprecation by Shrike82 · · Score: 1

      It's only being "removed" for some form of secure certification. Basically if you use it you can't have your software certified as "secure", whatever that means. It's not being removed from the language.

      --
      You can advertise in this sig from as little as £99.99 a month!
  18. Re:Let Java do it for you. by Anonymous Coward · · Score: 0

    Java in inefficient clumsy and bloated. For doing any serious computationally intensive apps C/C++ is still far more effective. The work I do couldn't even be managed in java and memory usage would go through the roof (we tried it 8gb++).

  19. Is that teen-speak? by Sybert42 · · Score: 0

    Wow, all this new lingo is confusing me. I bet everyone on Twitter knows it, though. Well...I memcpy you too!

  20. the worst offender is main() by JeanBaptiste · · Score: 5, Funny

    Most any security problem can be traced back to this function.

    1. Re:the worst offender is main() by Khashishi · · Score: 4, Funny

      you mean WinMain()

    2. Re:the worst offender is main() by JeanBaptiste · · Score: 1

      Get off my lawn.

    3. Re:the worst offender is main() by Albert+Sandberg · · Score: 1

      No, it's true. They trace back security problems to main() far far less than WinMain() =)

    4. Re:the worst offender is main() by WolfWithoutAClause · · Score: 1

      I forget the details but actually main isn't generally the first function called by the OS (there's initialisation before that); so no, not always ;-)

      --

      -WolfWithoutAClause

      "Gravity is only a theory, not a fact!"
  21. "memmove()" is safer than "memcpy()". by reporter · · Score: 2, Funny
    Though "memcpy()" is slightly faster than "memmove()", the latter is safer.

    As Windows products are now (and have been) mainstream products used extensively in banks and other financial institutions, reliability and security (RS) have prime importance. The speed that "memcpy()" gets you is not worth the price of reduced RS.

    1. Re:"memmove()" is safer than "memcpy()". by Anonymous Coward · · Score: 1, Informative

      The only "safer" thing about memmove is it can handle moves between overlapped regions. This is only reason to use memmove over memcpy. There is nothing safer about that.

  22. Not for C++ by mikael · · Score: 0

    Modern complex C++ class objects and structures, always seem to have a 'duplicate', 'transfer' or 'swap' function rather than a simple 'memcpy'.

    With a complex data structure with dynamically allocated linked lists, trees or chains of data, the assignment over '=' is rather ambiguous. Does it mean duplicate the contents, transfer the contents and clear the original copy, or just swap the contents of the items, which might be quicker.

    --
    Vintage computer adverts: http://www.vintageadbrowser.com/computers-and-software-ads
    1. Re:Not for C++ by JSBiff · · Score: 2, Insightful

      If = is ambiguous, then you must have a habit of abusing it. While you can overload = to mean anything you want, I suppose, it would seem like you should try to preserve the general notion of the assignment operator in C and C++, which is that = never modifies the right-hand side of the equal sign, only the left hand side.

      "Does it mean duplicate the contents, transfer the contents and clear the original copy, or just swap the contents of the items, which might be quicker."

      I would say if you are trying to stay true to the way the operator behaves in the language when you overload it, the last two operations would NOT be overloaded to the equal sign, because they modify the right-hand argument. Give them a meaningful method name instead.

    2. Re:Not for C++ by sqlrob · · Score: 2, Interesting

      = never modifies the right-hand side of the equal sign, only the left hand side.

      std::auto_ptr would like a word with you. This was one of the dumbest decisions the committee made.

    3. Re:Not for C++ by maxwell+demon · · Score: 1

      = never modifies the right-hand side of the equal sign, only the left hand side.

      std::auto_ptr would like a word with you. This was one of the dumbest decisions the committee made.

      Indeed. But the next version of the C++ standard will deprecate auto_ptr.

      --
      The Tao of math: The numbers you can count are not the real numbers.
    4. Re:Not for C++ by mikael · · Score: 1

      A discovery made by grinning idiots who love to cut and paste code and couldn't understand why they kept getting memory leaks and segmentation faults.

      By itself C++ will just create a default copy constructor going straight through to memcpy.
      I'll make an assignment operator a deep copy by default, and have all the different functions specified separately.

      --
      Vintage computer adverts: http://www.vintageadbrowser.com/computers-and-software-ads
    5. Re:Not for C++ by petermgreen · · Score: 1

      operator abuse seems to be an integral part of C++ style. Hell even the standard library does it ( auto_ptr, streams and possiblly strings depending on your view on whether string concatenation is close enough to addition).

      To understand whey lets consider why operators exist in the first place, "n=a+b+c+d+e" is a lot easier to read than "assign(n,add(a,add(b,add(c,add(d,e)))))". C++ doesn't let the coder create new operators (something mathematicians do on a regular basis) so the designer of a new type that could really do with a new operator is left with either using functions/methods (which leads to cluttered code in callers) or abusing an existing operator (which can lead to confusion).

      Letting coders create there own operators would be a nice (though possiblly problematic) feature for a language.

      --
      note: i'm known as plugwash most places but i screwd up registering that here somehow in the past and now can't register
  23. Re:Let Java do it for you. by tepples · · Score: 1

    Java, and other managed languages are the way to go.

    Until you're trying to do something for which Java has no standard API. Last time I checked, USB joysticks were like this. There is JInput, but if you include JInput in your distribution, your project is no longer 100% Pure Java and will not run as an applet.

    Or unless your target platform is incapable of running managed code. Some handheld platforms have only 4 MB of RAM, not enough for a JIT compiler and the bytecode in addition to the translated code except in trivial examples that act a generation old. And per Apple's developer agreement, the only managed language that can run on an iPod Touch is JavaScript in Safari.

    Or unless your existing program's model is written in an unmanaged language, and you want to reuse the old code so that you can be sure that the model is bit-for-bit accurate. How hard is it to automatically translate C code to, say, C++/CLI?

  24. Losing creative control by maclizard · · Score: 1

    This move my M$ is intended to remove creative solutions from the table. Granted, many creative solutions are used to undermined widely used software security, but this isn't the right solution. Unfortunately, I don't have any better ideas.

  25. Main squeeze? by Sybert42 · · Score: 0

    Oh that's so cute. Another emoticon! I'd like to say--main() you too!

  26. Silly and useless by ugen · · Score: 4, Insightful

    This is nothing like sprintf. In sprintf there is no way to know how much data will be created ahead of time, so limit on buffer size is useful to make sure there is no buffer overrun.

    With memcpy it is *precisely* known how much data will be copied. It is right there, 3rd parameter. If a developer can't do "if (sizetocopy = sizeofdstbuffer)", it is just as unlikely that he will be able to properly state that additional parameter that specifies the destination buffer size.

    Of course if Microsoft is so concerned with security, why the heck did it take them years to add snptinf()? All this is is another attempt to make crossplatform development that much harder (much like all those "obsolete" POSIX functions that will barf warnings unless you use a cryptic define).

    That said, if this silliness ever becomes a rule, I have an easy solution:
    #define memcpy(dst, src, size) memcpy_s((dst), (src), (size), (size))

    Problemo solved, now let's go actually write some real code.

    1. Re:Silly and useless by descil · · Score: 1

      If you're using the sprintf family you should definitely be making use of the size modifiers or at least checking your buffers before using any %s type escapes.

      If you just use snprintf you've not protected yourself against buffer underruns. Consider:

      void getUser(const char *uid)
      {
        char buf[52];
        snprintf(buf, 51, "select * from tbl where userid=%s and active=1", uid);
      }

      Here, if you have a userid that is padded with a few spaces, it doesn't matter if you're active or not.

    2. Re:Silly and useless by Tony+Hoyle · · Score: 1

      If it's possible for that to fail then you're already open to a number of exploits because you're using user data without validating it.

      If uid is "''; drop table tbl" you're screwed.

      Golden rule is - if you didn't generate the data yourself, it's untrusted. You certainly never sprintf it into a string.

      btw. you used a magic number. what if someone changes the size of buf without changing the second parameter? Don't do that.

    3. Re:Silly and useless by AndrewNeo · · Score: 1

      Which goes to prove why everyone should be using parametrized SQL.

    4. Re:Silly and useless by ComputerSlicer23 · · Score: 1

      Careful, you've just caused a different class of problems by you're macro. Well, actually you have the signature wrong, and then you've caused a problem. It is "memcpy(dst, dst_size, src, src_size)", the sizes go next to the appropriate pointers. Next, if size has any side affects the Macro you propose will cause the side affects twice. I forget the idiomatic way to resolve this is off hand, but check "Code Complete" or "Writing Solid C", I'm fairly sure they discuss the "right" way to handle this problem. While my hunch is that you're smart enough to know this, my guess is that too many C programmers don't realize the danger of such macros.

      However, this has the law of unintended consequences. Ulrich Drepper has some epic rants about why you shouldn't use any of the str* functions, and the logic is the same. If you are copying and you stop short in the copy, might be just as bad as going long. What is going to happen when the security problem is caused *BECAUSE* you didn't copy everything? The lack of a complete copy is silently truncated with no way for the caller to tell it happened. Well they can tell it happened, merely by duplicating the check in the call and then propagating the error. If nothing else, imagine a really long command line that ends with "rm -rf .kde", and I lined it all perfectly so that the all that is copied is "rm -rf .". We just have 30 years of experience to tell us that copying long is a problem. I'm curious if in 30 years, we'll have the experience to tell us that copying short is a problem also. Maybe, just maybe programmers should be very careful.

      Without the actual specs of memcpy_s, I'm not sure. This is my best guess as to the semantics. You're portability concern however is fairly laughable: #define memcpy_s(dest, dest_size, src, src_size) memcpy(dest, src, MIN(dest_size, src_size)) Assuming that the MIN correctly handles the parameters with side affects problem. People have been handling trivial portability concerns for a long time. The bcopy function comes to mind. I'm sure Autoconf will have this added as a standard macro inside of a month, but it is simple enough to implement yourself if you don't use autoconf or the like.

      Kirby

    5. Re:Silly and useless by caywen · · Score: 1

      From the perspective of a single, talented, and experienced developer, this all might seem silly. When one is managing many developers with varying skill levels, and are trying to maximize stability and security against a business ship date, telling everyone to add the if statement is just not going to be effective.

    6. Re:Silly and useless by harry666t · · Score: 2, Funny

      > if (sizetocopy = sizeofdstbuffer)

      ouch.

    7. Re:Silly and useless by Anonymous Coward · · Score: 0

      #define memcpy(dst, src, size) memcpy_s((dst), (src), (size), (size))

      No.

      #define memcpy(dst, src, size) memcpy_s((dst), (size), (src), (size))

    8. Re:Silly and useless by chebucto · · Score: 1

      With memcpy it is *precisely* known how much data will be copied. It is right there, 3rd parameter. If a developer can't do "if (sizetocopy = sizeofdstbuffer)", it is just as unlikely that he will be able to properly state that additional parameter that specifies the destination buffer size.

      Why not make a version of strcpy and memcpy that does its own sizeof(dst)? Leave the size parameter in there for cases where you want to copy less than the max size of the destination, but ignore the programmer when they give a size value that's larger than the actual sizeof(dst)...

      --
      The English word fart is one of the oldest words in the English vocabulary.
    9. Re:Silly and useless by Anonymous Coward · · Score: 0

      If a developer can't do "if (sizetocopy = sizeofdstbuffer)", [...]

      You, Sir, are the first to make me think that this move by MS is as a good one.
      Hint: Other people might have two equal signs ... and they might even have had a point.

      You screwed up by making a silly mistake anyone of us could have made. This new function at least might require one more silly mistake before being screwed.

    10. Re:Silly and useless by descil · · Score: 1

      I'd rather use "1 or 1" if someone let me put spaces and letters into their numerical inputs -- no nasty giveaway ' character -- but your point is taken, although you're ignoring mine.

      My point is you can't make sprintf or memcpy or anything in that language "safe." It's why all the idiots who would want a safe programming language now write buggy crashy slow Java programs. Thank god, nobody has managed to "fix" C yet.

      For the record, I don't generally use sprintf, I use myformat, a custom solution.

    11. Re:Silly and useless by descil · · Score: 1

      It's NOT that hard to sanitize input and keep your mind on your user's flow options. Parametrized SQL? Don't know anything about it: must be proprietary fud.

      It is MUCH HARDER to make and keep a program secure if it's written in a "secure language." These languages don't have as many pitfalls, so the programmer is not as aware and on the lookout for potential intrusions. If it's already all taken care of by the compiler, what need has the programmer to know about security? What need have they to know AES or DES, buffer overflow or multithreaded resource sharing?

    12. Re:Silly and useless by Anonymous Coward · · Score: 0

      If a developer can't do "if (sizetocopy = sizeofdstbuffer)"

      As a developer, I can't do that. That's assignment, not a test for equality.

    13. Re:Silly and useless by Anonymous Coward · · Score: 0

      Your 'easy solution' doesn't always work correctly and IS unsafe.

      If you pass a function to your size parameter, not only will it execute the function twice (performance degradation), but could potentially end up with different dst and src sizes. You're making a statement about the uselessness of Microsoft's approach and then provide a 'work-around' that actually PROVES why they're doing it in the first place!

      Remind me never to hire you as a programmer.

    14. Re:Silly and useless by rbarreira · · Score: 1

      Because if dst is a pointer, sizeof(dst) gives you the size of the pointer, not the size of the object it points to.

      --

      The AACS key is NOT 0xF606EEFD628B1CA427BEA93A9CA9773F
  27. When will MS learn? by coppro · · Score: 4, Insightful

    This is not the first time MS has done this. They have plenty of other standard functions that they have deprecated.

    Yes, you read that right. Microsoft is deprecating parts of an ISO Standard all by themselves. Not that this should surprise anyone. I would have absolutely no objection to them proposing to WG14 to deprecate those functions; heck, I'd encourage it! But besides going out and deciding to 'deprecate' parts of the standards, the replacement functions actually violate those same standards.

    And the warnings are irritating. You can't write a nice cross-platform library without either spewing tons of warnings or having to put in a bunch of #defines to shut the compiler up. And if you do that, your users get irritated if they depend on these warnings because you just turned them off (and of course, if you don't, they'll complain that your library is unsafe).

    Screw Microsoft.

    1. Re:When will MS learn? by theCoder · · Score: 4, Insightful

      In case anyone is curious, this is the type of thing that coppro is talking about:

          c:\Program Files\Microsoft Visual Studio 8\VC\include\io.h(318) : see declaration of 'close'
          Message: 'The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _close. See online help for details.'

      Now, as far as I know, no ISO body has deprecated functions like close(2), open(2), read(2), and write(2). And I've always heard that methods that start with an underscore are internal compiler functions and shouldn't be called directly. I don't know why the MS compiler writers think they can do this, but it is really annoying to get hundreds of warnings like this when compiling. In addition, it hides legitimate warnings that could indicate real problems.

      As to the article in question, I can't think of any good reason why memcpy(3C) would be considered unsafe, since it specifies the amount of memory to copy. Sure, you could use it to copy outside the bounds of dst, but that's just calling it incorrectly. It's not like sprintf(3C) where you could easily accidentally write outside the bounds of the string.

      --
      "Save the whales, feed the hungry, free the mallocs" -- author unknown
    2. Re:When will MS learn? by ausekilis · · Score: 1

      Yes, you read that right. Microsoft is deprecating parts of an ISO Standard all by themselves. Not that this should surprise anyone. I would have absolutely no objection to them proposing to WG14 to deprecate those functions; heck, I'd encourage it! But besides going out and deciding to 'deprecate' parts of the standards, the replacement functions actually violate those same standards.

      In order to deprecate parts of the ISO Standard, they'd first have to implement the ISO Standard. Granted I haven't looked over the MS C definition with a fine toothed comb, but all of my attempts at cross-platform development in C over the past decade have ended in fantastic failure because of MS taking something good (like the ISO standard), deciding it wasn't for them, and making their own version. They didn't conform to ISO in the first place. These 'deprecations' are really not much more than them making sure their broken functions have different names.

    3. Re:When will MS learn? by Anonymous Coward · · Score: 0

      They're deprecated in that in order to get a particular type of security certification that is largely used for internal applications, you should not use memcpy.

      It's still in the ISO standard and it's still accessible in their compiler!

    4. Re:When will MS learn? by Anonymous Coward · · Score: 0

      Was that in a ".c" file or in a ".cpp" file? They're two different languages with two different standards.

    5. Re:When will MS learn? by NullProg · · Score: 1

      As to the article in question, I can't think of any good reason why memcpy(3C) would be considered unsafe, since it specifies the amount of memory to copy. Sure, you could use it to copy outside the bounds of dst, but that's just calling it incorrectly. It's not like sprintf(3C) where you could easily accidentally write outside the bounds of the string.

      Agreed. I'll bet real money the Microsoft kernel developers will not be held to this standard either. Why would they want to waste cycles moving local fixed length structures/data blocks around.

      Enjoy,

      --
      It's just the normal noises in here.
    6. Re:When will MS learn? by Anonymous Coward · · Score: 0

      Identifiers that start with an underscore are in a reserved namespace, but you're free to call them. You just shouldn't define any new such identifiers yourself. And IIRC, I think close() was never an ISO C or C++ function to begin with; you're thinking of fclose(). The close() function was in fact a POSIX identifier, and Microsoft is deprecating POSIX compliance. Try turning on your compiler option for "strict ISO compliance" sometime, just to check out what it chokes on.

    7. Re:When will MS learn? by Tony+Hoyle · · Score: 1

      I have a header file around whose sole purpose is to switch all that crap off. There are a number of defines you can set to stop the deprecation warnings.

    8. Re:When will MS learn? by hackerjoe · · Score: 3, Insightful

      no ISO body has deprecated functions like close(2), open(2), read(2), and write(2)

      That's correct, because ISO C++ never included those functions in the first place. POSIX != ISO C. (Not that MSVC is on any kind of reasonable schedule for keeping up with ISO standards, but that's a whole different issue...)

      Basically MS is deprecating their own terrible implementation of some POSIX compatibility. This is actually required for ISO C compliance: the compiler is not supposed to define a bunch of extraneous functions in the global namespace, because they might conflict with your names. Once those functions are removed entirely (and I believe you can #define them away right now) you can implement your own compatibility functions for software you're porting to Windows.

      Now, this is all entirely separate from the SDL warnings GP is complaining about, which show up when you use standard ISO C functions like strcpy, sprintf, and apparently now memcpy. Which, honestly, I wish weren't quite so irritatingly implemented, although I'm torn because using those functions really is terrible.

      It's not really that worth getting up in arms about, though, because JESUS CHRIST there's a compiler flag to disable the warnings, just put it in your makefile and quit bitching already!

    9. Re:When will MS learn? by RightSaidFred99 · · Score: 1

      Screw drama queens.

      If a standard leads to poor quality code, insecure code, or other issues it's a bad standard. Adherence to the "standard" at all costs is the hobgoblin of little minds.

      Microsoft is not removing anything. Their deprecation means they do not recommend its use. That's it. You can still use it. More than likely you'll be able to specifically disable just that warning.

      Also, I don't think you understand the ISO standards. Adding functions to your compiler environment via headers or runtime implementation does not violate any standards.

    10. Re:When will MS learn? by querist · · Score: 1

      You can't write a nice cross-platform library...

      Ballmer: Curses! The Slashdot readers have discovered our true purpose! *throws chair*

    11. Re:When will MS learn? by RightSaidFred99 · · Score: 2, Interesting

      Wrong, wrong, wrong.

      open, close, etc.. are not in ISO C++. Functions not in the spec (vendor-specific) are supposed to have an _ in front.

      Any function you can think of (including strcpy) is "safe" if the developer specifies correct parameters. Whoopdy Do. That doesn't mean it's something that's easily verified by runtime checkers, static analysis, etc... That's why it's deprecated - it's easy to perform additional safety checks if you include both the source and destination sizes.

    12. Re:When will MS learn? by Anonymous Coward · · Score: 0

      ISO C does not define an open(), read(), write(), or close() function. I can't speak to ISO C++.

      ISO C does not restrict the language tools from offering those four functions, named as they are. It does not require that the functions be named with a leading underscore. Indeed, ISO C reserves any identifier that starts with an underscore; these identifiers are not available for definition in the source or by 3rd party packages.

      That Microsoft has decided to create internal compiler versions of some (otherwise) standard POSIX functions (this causing portability issues with POSIX code, and violating the spirit of the ISO C standard) only goes to show how Microsoft feels about portability, ISO and POSIX standards.

      That Microsoft now elects to remove from their own code an ISO C standard function (memcpy()), again goes to show how they feel about following language standards.

    13. Re:When will MS learn? by shutdown+-p+now · · Score: 2, Informative

      This is not the first time MS has done this. They have plenty of other standard functions that they have deprecated.

      Yes, you read that right. Microsoft is deprecating parts of an ISO Standard all by themselves.

      No, Microsoft isn't deprecating "parts of an ISO Standard" - only the standard committee can do that, by marking those parts as deprecated in the next version of the standard. Microsoft has enabled warnings on use of those "unsafe" functions by default, yes, but it is very much not the same thing.

      Regarding "all by themselves" part - do you realize that all those "safe" *_s functions are actually covered by an ISO C99 TR?. There's also a FOSS implementation available under the MIT license.

      And the warnings are irritating. You can't write a nice cross-platform library without either spewing tons of warnings or having to put in a bunch of #defines to shut the compiler up.

      You don't have to use #defines for that purpose, you use compiler flags in your makefile. You'll have to write one specifically for MSVC anyway (since it uses its own Make), so it's not a big deal.

      And if you do that, your users get irritated if they depend on these warnings because you just turned them off

      That doesn't make sense. If you turn them off for the code of your library, they're obviously not turned off for code of your users - unless you put #defines in your headers, which is obviously a dumb thing to do for many reasons (and I've already explained the proper way to do this above).

    14. Re:When will MS learn? by Anonymous Coward · · Score: 0

      Not only did they propose this to WG14, they also proposed it to WG21 (C++). Didn't fly.

      BTW, to turn these warnings off the proper way, don't use #define's but use a /D switch in the VC++ project file. In a sense, it's like /Za - make the ocmpiler behave a bit better.

    15. Re:When will MS learn? by Anonymous Coward · · Score: 0

      I don't like this because if I'm using strcpy, someone probably should smack me. This is not true of memcpy. Are there separate flags?

  28. Just use '=' by Anonymous Coward · · Score: 0

    The safe alternative is called '='. In standard C, you can just use the assignment operator between any data type (including struct and everything). The compiler will even type-check that assignment for you. That's probably one of the most underused features in C. I think it was introduced with C89, but the use of memcpy() was perpetuated by programmers raised on K&R.

    Yes, '=' doesn't do deep-copy, but neither does memcpy(). If that is an issue, use C++ and write an assignment operator.

    1. Re:Just use '=' by mrnobo1024 · · Score: 1

      You can't use assignment on arrays. (You could wrap an array in a struct just in order to allow assignment, but that's annoying, and it wouldn't help if you only want to copy part of an array.)

    2. Re:Just use '=' by Anonymous Coward · · Score: 0

      Yes, I agree with the safety of the "=" operator. It is a very versatile feature of C. You can even use it in the expression part of an "if" statement. How many other programming languages will let you do that?

    3. Re:Just use '=' by Anonymous Coward · · Score: 0

      You can use assignment on the first index quite easily, right?

    4. Re:Just use '=' by NewbieProgrammerMan · · Score: 1

      I don't think I've seen many instances of people using memcpy to copy structures; it generally seems to get used for copying contiguous blocks of data between buffers, and not much else. Maybe I haven't worked with enough suspender-wearing graybeards, though.

      --
      [b.belong('us') for b in bases if b.owner() == 'you']
    5. Re:Just use '=' by sqlrob · · Score: 1

      So how do you copy dynamically sized structures with = in C?

  29. if (dest_sz < copy_sz) throw; else memcpy(...); by tepples · · Score: 1

    Why? I can see some justification on the strXXX functions where you don't know how many bytes are going to be copied unless you call strlen first, but in memcpy you pass how many bytes to copy in as a parameter. So this is to protect programmers who can't do math?

    Yes. The article describes a replacement function memcpy_s that compares the copy size to the destination buffer size and throws an exception if the copy size is larger. It's still unsafe if the program lies to memcpy_s about the destination buffer size, and now it appears to needs exception support in the runtime (which based on my tests can add an extra 64 KB to your elevator controller's firmware).

  30. Good start by Anonymous Coward · · Score: 0

    Now ban the rest of the C library, and then ban the C language itself.

    Oh lol, captcha for this post is Pervert.

  31. Voodoo to me by Sybert42 · · Score: 0

    I noticed it worked one time, but thought one of our targets would whine about it.

  32. Think about it by Slothrup · · Score: 0

    Some of these reactions are quite funny.

    The goal of asking you to specify the length of the destination buffer is to force you to think about the data you're working with *while* you're writing the code and not afterwards in an unconnected security audit. Furthermore, it provides documentation to other people reading the code who may not have the same mental model of what's going on as you do. And as usual "other people" includes you, six months after you wrote the code.

    --
    The difference between theory and practice is that, in theory, there is no difference between theory and practice.
    1. Re:Think about it by TrekkieGod · · Score: 2, Insightful

      Some of these reactions are quite funny.

      The goal of asking you to specify the length of the destination buffer is to force you to think about the data you're working with *while* you're writing the code and not afterwards in an unconnected security audit. Furthermore, it provides documentation to other people reading the code who may not have the same mental model of what's going on as you do. And as usual "other people" includes you, six months after you wrote the code.

      Uh-huh. Because everyone is not just going to add a line of code to one of the base headers:

      #define memcpy(dst, len, src) memcpy_s((dst),(len),(src),(len))

      C is not a safe language, and stupid programmers will always find ways to mess it up. There are safer languages where you can't hang yourself as easily, and if you don't understand C, you should use them. Microsoft can't fix this problem.

      --

      Warning: Opinions known to be heavily biased.

    2. Re:Think about it by Slothrup · · Score: 0

      C is not a safe language, and stupid programmers will always find ways to mess it up. There are safer languages where you can't hang yourself as easily, and if you don't understand C, you should use them.

      The idea that smart people don't make mistakes is thoroughly ridiculous.

      Because everyone is not just going to add a line of code to one of the base headers:
      #define memcpy(dst, len, src) memcpy_s((dst),(len),(src),(len))

      Smart people recognize that they make mistakes, so they create systems that help them catch and prevent their own mistakes. If you're foolish enough to believe that you can't make mistakes, then you should just turn off all the warnings on the compiler and not bother with lesser workarounds like redefining a single symbol.

      --
      The difference between theory and practice is that, in theory, there is no difference between theory and practice.
    3. Re:Think about it by TrekkieGod · · Score: 2, Interesting

      The idea that smart people don't make mistakes is thoroughly ridiculous.

      They make mistakes, they don't make that mistake.

      Smart people recognize that they make mistakes, so they create systems that help them catch and prevent their own mistakes. If you're foolish enough to believe that you can't make mistakes, then you should just turn off all the warnings on the compiler and not bother with lesser workarounds like redefining a single symbol.

      That's not the issue. The new function is still relying on the programmer not making a mistake. What makes you think that anyone who would make a mistake on the number of bytes to copy wouldn't make a mistake on the size of the buffer? Alternatively, what happens if the src buffer size isn't large enough? Do we need to add another length parameter here?

      I have nothing against making a language safer, but if the language can't ensure the size of the buffers itself (and it can't in this case), relying on the programmer to pass in the correct number is exactly as safe as relying on the programmer to do the bounds checking. Exactly as safe, no safer.

      --

      Warning: Opinions known to be heavily biased.

    4. Re:Think about it by RightSaidFred99 · · Score: 1

      It is safer. I can use runtime and static analysis tools to check the source and destination sizes. I can even verify via tools if the two 'len' args refer to the same variable.

    5. Re:Think about it by Anonymous Coward · · Score: 0

      I can use runtime and static analysis tools to check the source and destination sizes.

      You can use static analysis tools only if source and destination are not dynamic. But if source and destination are not dynamic, then you can use static analysis to check the call of memcpy().

      If you do a runtime check for sizes, then you might as well do a runtime check of sizes before you call memcpy.

      In neither case does memcpy_s buy you anything.

    6. Re:Think about it by k8to · · Score: 1

      It's less safe, because it's more complicated.

      Not by a lot, of course, but the two numbers makes it just that much harder to easily determine the behavior.

      --
      -josh
    7. Re:Think about it by NoOneInParticular · · Score: 1
      The braindeadness comes from the fact that memcpy and memcpy_s have completely different contracts. So now people will port code that reads:

      int mem_copy(void* dst, int dstlen, void* src, int srclen, int tocopy) {
      if (dstlen < tocopy || srclen < tocopy) return ERR_NOSPACE;
      memcpy(dst, src, tocopy);
      }

      To (incorrectly)

      int safe_copy(void* dst, int dstlen, void* src, int srclen, int tocopy) {
      if (dstlen < tocopy || srclen < tocopy) return ERR_NOSPACE;
      memcpy_s(dst, dstlen, src, srclen); /* BUG: we quite likely copy more than we should */
      }

      Or (correctly to)

      int safe_copy(void* dst, int dstlen, void* src, int srclen, int tocopy) {
      if (dstlen < tocopy || srclen < tocopy) return ERR_NOSPACE;
      memcpy_s(dst, tocopy, src, tocopy); /* misuse buflen to specify what to copy */
      }

      So, to port this code, we have to break the implicit contract with memcpy_s that asks us to provide the length of the buffers instead of the number of bytes that we would like to copy. Your static analysis tools would incorrectly flag the correct version as incorrect, and you might even change the second version to the first to 'fix' it.

      If MS would have provided 'safe_copy' as 'memcpy_s' this would be fine. memcpy_s is not a memcpy, it is a bufcpy. If MS is serious about security, it should ban memcpy_s, not memcpy.

    8. Re:Think about it by RightSaidFred99 · · Score: 1

      Wrong. It would be memcpy_s(dst, dstlen, src, tocopy). I don't see your point either way. The final parameter is not a buffer size. It is the number of bytes to copy. There is exactly one specification of a buffer size, and that is for the destination.

  33. Competent coders? by Anonymous Coward · · Score: 0

    Hey Microsoft, instead of banishing a function that is perfectly safe and standardized for decades why not hire competent programmers to begin with? I mean, the function copies a fixed number of bytes from an object to a pointer. How hard is it to understand that you need to allocate memory and that writing to a memory location that isn't yours is a bad thing?

    Seriously, what idiots are doing the hiring and training in that company?

  34. Workaround by pensivepuppy · · Score: 2, Insightful

    #define memcpy(s1, s2, n) memcpy_s((s1), (n), (s2), (n))

  35. Typically Bad Summary by Nom+du+Keyboard · · Score: 0, Redundant

    Another bad Slashdot summary. Safer alternatives (e.g. memcpy_s) are already in place, but somehow that wasn't mentioned up where it should have been.

    Bad Slashdot editors -- no soup for you!

    --
    "It's the height of ridiculousness to say for those 9 lines you get hundreds of millions."
  36. Bootleg memcpy() Moonshine . . . by PolygamousRanchKid+ · · Score: 1

    . . . so ban it. If I really need it, I'll write my own. What happened when the US banned alcohol? Bootlegged Moonshine.

    " . . .do you think it will restrict the creativity of the programmer?"

    Quite the opposite, it will inspire them to find other creative ways around the restrictions.

    Oh, and you can grep your code and say, "Look! No memcpy()! I'm secure!" But what about self-written functions that does the same thing as memcpy(), with 1,000 different names?

    --
    Schroedinger's Brexit: The UK is both in and out of the EU at the same time!
  37. Re:if (dest_sz copy_sz) throw; else memcpy(...); by maxwell+demon · · Score: 1

    Indeed, throwing an exception is the worst thing you can do to such a low-level function (and yes, memcpy is about as low level as you can get).

    High-level C++ code shouldn't use memcpy, simply because it's too low-level (it won't even work correctly if there's a non-trivial copy constructor). Use std::copy instead. For low level code, memcpy makes sense, but exceptions don't.

    Why not just doing the same as the strnXXX functions, i.e. just stop copying at the end of the destination buffer? That is, just implement it as

    memcpy(dest, src, min(destsize, srcsize));

    --
    The Tao of math: The numbers you can count are not the real numbers.
  38. Re:Let Java do it for you. by feldicus · · Score: 1

    How hard is it to automatically translate C code to, say, C++/CLI?

    My guess would be less difficult than first suspected, but fairly laborious.

    feldicus

  39. Pure Python != panacea by tepples · · Score: 1

    Or you can use a general purpose language and be done with it.

    Python has its uses, but it also has its overhead. Good luck getting any kind of performance with pure Python code on a handheld device with 4 MB of RAM and a 67 MHz CPU. Or good luck getting a good frame rate with a graphics engine that uses PyOpenGL. (And why is the snake wrapping itself around EA Games' old box-ball-cone logo?)

    1. Re:Pure Python != panacea by maxwell+demon · · Score: 1

      I guess he just saw that the link leads to some page at perl.org, didn't follow the link, wrongly assumed that it led to some Perl advocacy, and decided to put his Python link against it.

      --
      The Tao of math: The numbers you can count are not the real numbers.
    2. Re:Pure Python != panacea by SanityInAnarchy · · Score: 1

      Or good luck getting a good frame rate with a graphics engine that uses PyOpenGL.

      Has this been tried?

      --
      Don't thank God, thank a doctor!
    3. Re:Pure Python != panacea by Lokitoth · · Score: 1

      Good luck targetting a handheld device with 4 MB of RAM and a 67 MHz CPU with Microsoft's SDK/c compiler? If you can manage this, surely you can deal with the warning that it would generate from using memcpy, yes?

      Just because all you happen to see are nails, does not mean that a hammer should be your only tool.

      Seriously, this is a security guideline. They are not removing anything from the language. They are not forcing you to deal with this. If your company treats warnings as errors, schedule a process meeting and add this particular warning to the list of ignored warnings.

      Talk about much ado about nothing.

  40. Too easy! by alexborges · · Score: 1

    In soviet russia...

    --
    NO SIG
  41. Stop protecting me from me! by BitZtream · · Score: 4, Interesting

    As a competent developer, I get extremely annoyed by this sort of shit.

    Removing/banning memcpy doesn't change a damn thing cause the first thing I do with things that have to compile in VisualStudio now is add the following defines which turn this shit off:

    _CRT_SECURE_NO_WARNINGS
    _CRT_NONSTDC_NO_DEPRECATE

    If the remove that option I'll simply add memcpy to my standard MS compatibility library that deals with all the other bullshit MS decides to do.

    You can't fix stupid. Stop trying. People fuck up VB and C# apps just as much as the fuck up C and C++ apps. So they don't do it with a buffer overflow, they do it by shear stupidity. You'll be more secure by taking away languages that allow non-programmers to pretend to be programmers than making it harder on those of us that are just going to work around what you do anyway.

    You're not going to fix broken shitty apps with exploits by removing functions, the functions aren't the problem they do exactly as they are told (or atleast they are supposed to :). You need to fix the programmers who can't clarify what they want done.

    http://www.xkcd.com/568/
    Second pane:
    You'll never find a programming language that frees you from the burden of clarifying your ideas.

    --
    Persistent Volume manager for Kubernetes - https://github.com/dwimsey/openshift-pvmanager
    1. Re:Stop protecting me from me! by m50d · · Score: 1
      You can't fix stupid. Stop trying. People fuck up VB and C# apps just as much as the fuck up C and C++ apps.

      No - and when they do, the security implications are much smaller. Yes, it is always going to be *possible* to write an insecure program - but that doesn't mean the likelihood is the same.

      Now that said, I disapprove of these measures - simply because if you could afford the efficiency problems they introduce, you shouldn't be using C at all.

      --
      I am trolling
    2. Re:Stop protecting me from me! by bostei2008 · · Score: 1

      As a competent developer, I get extremely annoyed by this sort of shit.

      I could not agree more.

      Simple rules like "don't use goto/printf/memcpy/..." give you a false sense of security (or, accomplishment). It is perfectly possible to write completely f** up moronic code while following all such quality standards by the letter.

      You'll never find a programming language that frees you from the burden of clarifying your ideas.

      Simple rules never should replace thinking. Unfortunately, they often do.

    3. Re:Stop protecting me from me! by Osso · · Score: 1

      I'm looking forward to:

      from __future__ import clarify
      clarify(my_fun)

    4. Re:Stop protecting me from me! by BikeHelmet · · Score: 1

      You'll be more secure by taking away languages that allow non-programmers to pretend to be programmers than making it harder on those of us that are just going to work around what you do anyway.

      How do you fix the programmers, though?

      I started coding with HTML/Javascript, then Java. I assure you, I'd never make a foolish mistake like copying too much data into a buffer.

      But a remarkable number of sites are poorly coded, so how exactly do we find the problem programmers, let alone fix them?

    5. Re:Stop protecting me from me! by halber_mensch · · Score: 1

      People fuck up VB and C# apps just as much as the fuck up C and C++ apps. So they don't do it with a buffer overflow, they do it by shear stupidity.

      I am picturing a bunch of VB programmers running down the hall with scissors... and the way it ends makes me smile...

      --
      perl -e "eval pack(q{H*},join q{},qw{70 72696e74207061636b28717b482a7d2c717b343 637323635363534323533343430617d293b})"
  42. Re:A Good Thing by whiledo · · Score: 1

    It should be noted that it does make it harder to do the wrong thing, when memory leak tools test the code.

    --
    Moderators: Before moderating a comment Insightful/Informative, check to see if a child post has already refuted it.
  43. As a C#/Java guy... by Schnoogs · · Score: 0

    ...I'll just have to assume this is a good thing and take it from you C/C++ guys.

  44. Drool proof? by Stavr0 · · Score: 1

    How long until someone circumvents that with a while() with strncpy() and strlen() inside?

    1. Re:Drool proof? by SL+Baur · · Score: 1

      Forever. The two are not equivalent and your version will be painfully slow if copying a zeroed block of memory.

  45. Efficiency by KalvinB · · Score: 1

    As long as the new version is just as efficient then there's not really an issue. Not everyone likes to play the MHZ card to justify bloated, inefficient code.

    Removing the functionality or crippiling it is as stupid as requiring training wheels on all bikes because some people fall down and hurt themselves.

    1. Re:Efficiency by beej · · Score: 1

      I'm sure the time complexity of memcpy_s is the same as memcpy. We can hope they only test against the max length one time, and not inside the loop. :)

  46. easy fix by Chris+Snook · · Score: 4, Insightful

    Just write a one-liner that replaces all calls to memcpy with a call to memcpy_s, duplicating the size parameter.

    I'm only half-joking. This is exactly how people will (mis)use memcpy_s. If you want safe memory access, you need to ban the entire C language. For those cases where you need C, you'll just have to make sure your programmers know what they're doing.

    --
    There's no failure quite as dissatisfying as a complete and total solution to the wrong problem.
    1. Re:easy fix by Anonymous Coward · · Score: 0


      If you want safe memory access, you need to ban the entire C language.

      Yeah, they need to rewrite the JVM/ILM in assembler anyway, they were too slow and bloated to begin with. The Python/PHP/Perl/xxx interpreters should be rewritten using VB3.

    2. Re:easy fix by Anonymous Coward · · Score: 0

      Just write a one-liner that replaces all calls to memcpy with a call to memcpy_s, duplicating the size parameter.

      I'm only half-joking. This is exactly how people will (mis)use memcpy_s. If you want safe memory access, you need to ban the entire C language. For those cases where you need C, you'll just have to make sure your programmers know what they're doing.

      Nice lets ban C and abstract all programming by using java or the likes... nice choice moron!

      Why dont we just hire monkeys!

    3. Re:easy fix by bostei2008 · · Score: 1

      this is exactly what I will do for any code I have to port to windows.

    4. Re:easy fix by speculatrix · · Score: 1

      headline: Microsoft Ban Stupid Developers

      in a shock new move, Microsoft announce their development tools will require an IQ test to complete product activation.

      In other news, microsoft have posted job adverts for 10,000 new developers, to replace the hordes of low grade programmers they previously hired who can't pass their IQ tests.

  47. How to easily ... by DemoLiter3 · · Score: 4, Insightful

    How to easily make your code compliant with the new safety requirements:

    #define memcpy(dest,src,len) memcpy_s(dest,len,src,len)

    1. Re:How to easily ... by frieko · · Score: 1

      Huh?? It is just as bad to copy the first 80 bytes of a 40-byte string into an 80-byte buffer as it is to copy an 80-byte string into a 40-byte buffer. How is your code not simply "pretending" to comply?

      Disclaimer, talking out of my ass here.

    2. Re:How to easily ... by jdoverholt · · Score: 3, Informative

      Not quite "just as bad," in my opinion. Writing outside of your boundary is much more likely to cause problems (overwriting other things) than reading out of bounds. A 40-byte null-terminated string, for instance, wouldn't be hurt by another 40 bytes of heap data, so long as the null terminator was intact. You may still throw an error if it's not your memory that's being read. Just saying... writing (approx. equals) 100% trouble, reading < writing.

    3. Re:How to easily ... by cool_story_bro · · Score: 5, Informative

      He didn't say "how to make your code safe." He said "how to make your code comply with the safety standards." Rarely are the two the same. It's perfectly possible to safely use memcpy(), just like it's perfectly possible to abuse about a billion other system calls.

      --
      You must wait a little bit before using this resource; please try again later.
    4. Re:How to easily ... by Anonymous Coward · · Score: 0

      Way to go with the first-post-attachment karma whoring ;) An' I had mod points, you'd be offtopic.

    5. Re:How to easily ... by mysidia · · Score: 1

      Reading outside the heap-allocated region may produce a segfault. Leading to a possible DoS vulnerability in your application under certain conditions.

      Also, there is a possibility you could be making an unintended copy of security-sensitive data that won't be properly scrubbed when your subroutine exits.

      This means other vulnerabilities in a different subroutine probably results in easy disclosure of the sensitive data to a hacker.

    6. Re:How to easily ... by Joce640k · · Score: 1

      I agree that in practical terms this achieves nothing (the million comments below will conform this).

      On the other hand, it might some value in places which have code reviews and for people who now have to redo every instance of memcpy in existing code to make it compliant.

      Besides, you very rarely need memcpy in a C++ program so it's no big deal.

      --
      No sig today...
    7. Re:How to easily ... by Anonymous Coward · · Score: 1, Informative

      memcpy() isn't a syscall.

  48. memcpy in C++ by loufoque · · Score: 1

    The only use there is in C++ for usage of memcpy is when you want to run afoul the strict aliasing rules.

    Otherwise, you use std::copy.

    1. Re:memcpy in C++ by Tony+Hoyle · · Score: 1

      There are some cases using raw data, but for any complex types you're right. And for those you just use =

  49. The wole thing is just a bunch of nonsense by LanceUppercut · · Score: 5, Insightful

    Firstly, the specification of C anf C++ standard library is governed by the corresponding standard commitee. Microsoft has absolutely no authority to "banish" anything from neither C nor C++. They can deprecate it in their .NET code, C# etc., but it has absolutely no relevance to C and C++ languages. So, why would the author of the original question direct it to "advanced C and C++" programmers is beyond me. In general, C and C++ programmers will never know about this "interesting" development.

    Secondly, the tryly unsafe and useless functions in the C standard library are the functions like "gets", which offer absolutely no protection agains buffer overflow, regardless of how careful the develoiper is. Functions like 'memcpy', on the other hand, offer sufficient protection to a qualified developer. There's absolutely no sentiment against these functions in C/C++ community and there is absolutely no possiblity of these functions to get deprecated as long as C language exists.

    1. Re:The wole thing is just a bunch of nonsense by shutdown+-p+now · · Score: 1

      Firstly, the specification of C anf C++ standard library is governed by the corresponding standard commitee.

      Indeed.

    2. Re:The wole thing is just a bunch of nonsense by Lousewort+Logger · · Score: 1

      Secondly, the tryly unsafe and useless functions in the C standard library are the functions like "gets", which offer absolutely no protection agains buffer overflow, regardless of how careful the develoiper is.

      Very true. On the other hand, how many command line programs are written for win32 these days? There is really no good reason for MS to deprecate "gets".

      For that matter, how is memcpy_s any safer than memcpy? If you specify a length argument that exceeds buffer size it will overrun anyway, regardless of the function you use. Their whole doggarn problem is with pointers. I don't think the ms devs understand them at all.

      MS should leave the ISO standard alone. There's nothing wrong with it. Rather, they should concentrate on fixing their holy OS (as in an OS full of holes) and hiring devs that actually understand programming.

  50. Re:Let Java do it for you. by Anonymous Coward · · Score: 0

    Fail.
    You clearly don't know what you're doing. Anything a non-managed language can do, a managed language can do. The only things that should be coded in C are (parts of) OS and embedded code. CPU is cheap, tracing down buffer overflows and segfaults is expensive. And for your dataset...did you make every piece of information its own class? I bet you did, didn't you. Incompetent failure...go back to IT Tech.

  51. Unterminated string by tepples · · Score: 1

    Why not just doing the same as the strnXXX functions, i.e. just stop copying at the end of the destination buffer?

    Because the copy functions are often used to copy array-lists whose end is defined by a sentinel value. You might recognize C strings, which are array-lists terminated with a '\0' character. Using min() doesn't guarantee that the sentinel value gets written. It'd be safer than plain memcpy() in that it can't overwrite the data after the destination buffer (if the size is accurate), but reading from that unterminated buffer probably still leaves a hole for some attacks.

  52. elevator firmware runs Windows? by Gary+W.+Longsine · · Score: 1, Funny

    Oh, stars above, what have we done...

    --
    If you mod me down, I shall become more powerful than you could possibly imagine.
    1. Re:elevator firmware runs Windows? by jonaskoelker · · Score: 1

      elevator firmware runs Windows?

      Where would you like to go today?

  53. I don't know what version of memcpy they're using by Punto · · Score: 1

    but mine already has an argument for the size of the destination buffer, it's the third parameter. Why not just update the documentation? Are they really just adding a second size parameter, just to compare them? or will they use min(size1, size2) on the actual memcpy call, so that nobody knows exactly how much data is copied anymore? you don't want to read past your src buffer after all, right?

    --

    --
    Stay tuned for some shock and awe coming right up after this messages!

  54. How will they know ... by PPH · · Score: 1

    ... if I'm still using it as long as I'm not using Microsoft tools to write/compile my source?

    --
    Have gnu, will travel.
  55. Re:Let Java do it for you. by Anonymous Coward · · Score: 0

    WHOOOOOOOOOOOOOSH.

  56. Shooting themselves in the foot. by Dimwit · · Score: 2, Insightful

    Now, all that's going to happen is that programmers are going to write their own memcpy-like routines using a quicky for-loop or something. It'll be just as bug prone, and harder to detect via automated source code analysis.

    --
    ...but it's being eaten...by some...Linux or something...
    1. Re:Shooting themselves in the foot. by GleeBot · · Score: 3, Interesting

      Now, all that's going to happen is that programmers are going to write their own memcpy-like routines using a quicky for-loop or something. It'll be just as bug prone, and harder to detect via automated source code analysis.

      Not to mention it'll be slower. memcpy is one of the most optimized functions in any C library. It's frequently handled as a compiler intrinsic, that can do stuff like unroll short copies, generate optimal machine code, etc.

    2. Re:Shooting themselves in the foot. by eulernet · · Score: 1

      No, this is strictly equivalent when you compile with optimizations.

      When you compile a for-loop where you copy one element, the compiler replaces it with a memcpy on all the array.

      However, when you run instrumented code or code without optimizations, it's a PITA, since copying element by element is much slower (and with instrumented code, it's probably 10 times slower).

    3. Re:Shooting themselves in the foot. by LightningTH · · Score: 1

      Actually, memcpy in and of itself is slow. Hand writing your own asm version of memcpy using extended cpu functions is a lot faster as memcpy itself is usually kept basic enough to work on any cpu, including the older cpu's without MMX, SSE, etc.

    4. Re:Shooting themselves in the foot. by Anonymous Coward · · Score: 0

      No, this is strictly equivalent when you compile with optimizations.

      When you compile a for-loop where you copy one element, the compiler replaces it with a memcpy on all the array.

      Maybe in an ideal world. It's hardly "strictly equivalent".

      Take the (C99) definition of memcpy(); it uses the restrict keyword to explicitly prohibit aliasing. If you alias, you're breaking the specification of the function and the compiler is allowed to behave in an undefined manner.

    5. Re:Shooting themselves in the foot. by Anonymous Coward · · Score: 0

      Actually, memcpy in and of itself is slow. Hand writing your own asm version of memcpy using extended cpu functions is a lot faster as memcpy itself is usually kept basic enough to work on any cpu, including the older cpu's without MMX, SSE, etc.

      Incorrect. The libc version of memcpy may be slow and generic. GCC doesn't use the library version of memcpy, at least on most platforms, but an intrinsic called __builtin_memcpy (there are also intrinsics for things like vector operations, among other fun things).

      GCC's version of memcpy is architecture-specific, and often has been specifically coded for MMX, SSE, whatever, depending on the optimization flags in effect. Ironically, often it's faster not to use these special instructions.

      Hand-rolling your own memcpy routines in assembly isn't only more labor-intensive and non-portable (not to mention more difficult to inline and unroll), it may well perform more slowly than one written by the GCC maintainers, benchmarked against a wide range of architectures and sub-architectures.

      Speeding up byte shuffling is a pretty important function of any optimizing compiler, so it gets a lot of attention paid to it, more so than more esoteric fields of optimization, like automatic vectorization.

    6. Re:Shooting themselves in the foot. by Just+Some+Guy · · Score: 3, Interesting

      Actually, memcpy in and of itself is slow. Hand writing your own asm version of memcpy using extended cpu functions is a lot faster as memcpy itself is usually kept basic enough to work on any cpu, including the older cpu's without MMX, SSE, etc.

      glibc contains specific implementations for sparc32, powerpc32, powerpc64, i386, i586, cris, i860, rs6000, and m68k. I don't know where you got your idea.

      --
      Dewey, what part of this looks like authorities should be involved?
  57. Good. by JustNiz · · Score: 1

    Microsoft yet again demonstrating they believe everyone in the world except them only deserves plastic scissors.

    I hope that in the name of safety, Microsoft continue to remove all remaining potentially useful functionality so that eventually even developers wont be able to do anything productive with their products at all.

    Then finally, even consumers and upper managers will have to understand how shitty Microsoft products are, so will stop buying and enforcing the use of Microsoft products on the rest of us.

    1. Re:Good. by RightSaidFred99 · · Score: 1

      What in God's name are you talking about? Did you read the article and do you know anything about software or C++?

    2. Re:Good. by JustNiz · · Score: 2, Funny

      Yes and yes. I've been a developer for over 30 years now(nearly all C or C++). How about you?

  58. Re:Let Java do it for you. by maxwell+demon · · Score: 1

    Java? Unlambda!
    <marketingspeak>

    • No explicit managing of memory!
    • All programs are automatically typesafe! (there's only one type: function of one argument)
    • The full power of functional programming! All your programs will be fully functional as soon as they pass the syntax test!
    • Easy to learn syntax!

    </marketingspeak>

    --
    The Tao of math: The numbers you can count are not the real numbers.
  59. Quit kicking a dead horse and just use Ada by Anonymous Coward · · Score: 1, Funny

    Silly humans. Use Ada if you want to build something that works.

  60. Re:Let Java do it for you. by Anonymous Coward · · Score: 0, Troll

    If you wrote a program that used 8+ gigs of memory that means you're an incompetent code monkey.

  61. Re:Let Java do it for you. by samweber · · Score: 2, Interesting

    Until you're trying to do something for which Java has no standard API. Last time I checked, USB joysticks were like this. There is JInput, but if you include JInput in your distribution, your project is no longer 100% Pure Java and will not run as an applet.

    But your C/C++ code is never able to be run as an applet, while Java code might. So, on these grounds Java is better.

    Or unless your target platform is incapable of running managed code. Some handheld platforms have only 4 MB of RAM, not enough for a JIT compiler and the bytecode in addition to the translated code except in trivial examples that act a generation old.

    And for that we have Java ME edition.

    Okay, there are devices that are even more tiny in which C or assembly is the only option. I've also dealt with a processor that couldn't be programmed in C without extensive non-standard C extensions. Either way, this is a small minority of situations -- there is no one solution that suits all purposes.

    And per Apple's developer agreement, the only managed language that can run on an iPod Touch is JavaScript in Safari.

    And they allow just any old C code to run?!!

    Or unless your existing program's model is written in an unmanaged language, and you want to reuse the old code so that you can be sure that the model is bit-for-bit accurate. How hard is it to automatically translate C code to, say, C++/CLI?

    Eeek! Don't do this!

    If you want bit-by-bit accuracy, you absolutely don't want to try translating C code to C++! You even have to worry about changing C compilers if you are doing that. (And yes, I have worked with C code which would break if we used a different compiler. It was not fun.)

    What you should be thinking of doing is to write an interface between the existing model code and your new one. This can be done in both C++ and Java. When the new code has to manipulate the model, it goes through this interface and calls the old code to do the necessary operation.

  62. Re:Let Java do it for you. by tepples · · Score: 2, Interesting

    And for [platforms with small CPU and small RAM] we have Java ME edition.

    That is, if your platform vendor offers a port of Java ME.

    If you want bit-by-bit accuracy, you absolutely don't want to try translating C code to C++! You even have to worry about changing C compilers if you are doing that.

    I already test my code on GCC targeting x86 and ARM. Or did you mean compilers that a hobbyist looking to start a business can't easily afford?

    What you should be thinking of doing is to write an interface between the existing model code and your new one. This can be done in both C++ and Java. When the new code has to manipulate the model, it goes through this interface and calls the old code to do the necessary operation.

    Mostly I was thinking about trying to port an existing video game to a phone that runs Java ME MIDP or a game console that runs XNA, while preserving frame-for-frame accuracy of the physics. You can't run the old model on such hardware because you don't have the certificate to digitally sign native code. Or did your "interface" include communication over a network to a server running the model?

  63. meh by mach1980 · · Score: 1

    I've just finished evaluating approximatley 500kloc code using Coverity Prevent and Klocwork Insight (Static analysis tools). Together they found around 250 issues with the code. Null pointer dereferences, array boundary violations and a bunch of other nasty stuff.
    How many of these do you think involved memcpy? - Nil, Zip, Nada.

    --
    Break the sound barrier - bring the noise.
  64. memcpy_s is totally safe! by Anonymous Coward · · Score: 0

    According to MSDN docs, memcpy_s takes the size of the destination buffer as the second parameter. Gee, that's easy! memcpy_s(&dest[offset], sizeof dest, src, count);

    Except, oh wait, if you write "sizeof dest" bytes starting from the middle of dest, that can still overflow.

    The fact is, this doesn't affect security AT ALL. If someone's enough of an idiot that they can't even use a function as simple as memcpy safely, they'll find a way to screw up memcpy_s too. You want secure code, Microsoft? Stop letting morons write code!

  65. Re:if (dest_sz copy_sz) throw; else memcpy(...); by Anonymous Coward · · Score: 0

    On Windows, it throws if you access unmapped memory, even in your own code.

  66. Oblig. XKCD by Anonymous Coward · · Score: 0
  67. Look for a 50% performance hit by Anonymous Coward · · Score: 0

    Unwise move by Micro$lop, or perhaps another 'subvert Linux' attempt.
    Firstly, in the grand scheme of things, memcpy() is NOT a source of very many security problems. Maybe it is for the Microsoft-way-of-coding it is, but that's a self-inflicted bit of stupidity. Speaking from many years of developing an enterprise-grade HIPS (Host Intrusion Prevention System).
    Secondly, memcpy() is one of the key performance routines for any computer system. This is one of the handful of routines which is perpetually written in assembly, hand unrolled, does prefetching, and is highly aware of cache lines/sizes.
    Hmmm - wait a minute, this is great for me - I currently work at a chip company, and this will require everyone to buy much faster CPUs!

  68. They'd also have to ban..... by Ancient_Hacker · · Score: 1

    If memcpy() is hazardous, that means they also need to ban any operations that can mimic its effects, such as for loops, array indexing, ++ and --. And any call to read() or fread(). That sure would tighten things up!

  69. what C really needs by speedtux · · Score: 1

    What C really needs is variants of malloc and mem* that actually explicitly and officially keep track of the sizes of the allocated buffers.

    Right now, you can get that during debugging with valgrind, but you don't get those checks at runtime.

  70. Microsoft Can't Deprecate POSIX Functions by Anonymous Coward · · Score: 1, Insightful

    Besides:

    #pragma warning( disable: 4996 )

    Thanks

  71. Lock in from Microsoft by wandazulu · · Score: 4, Interesting

    There have been several suggestions to replace memcpy with memcpy_s as the safer alternative. That's fine, I guess, if memcpy_s is part of the ANSI/ISO standard for C, which as far as I know, it is not; just like all the *_s functions.

    Microsoft says your code is safer when using the *_s, but it will no longer be portable, it'll be Microsoft-only. They put in a warning in the compiler from VS2005 onwards about using "unsafe" functions, and that you should use *_s, which is a pain because you have to disable it as the project level, there doesn't seem to be anywhere that I've found that can just turn it off permanently. Even using the STL that comes with VS2008 will generate these warnings, even if you never do any explicit memory stuff yourself.

    Microsoft did the same thing with the _* functions; a lot of them are just wrappers around their ANSI-compliant versions (_sprintf -> sprintf), but are also not portable; I worked with a guy who wrote/tested all his C code in VS6 then gave it to me to port to Unix and VMS, and the compilers would choke on not having these particular functions.

    Microsoft is trying to get lock-in at the language level instead of providing a good set of Win32 API-based functions that make using memcpy() unnecessary.

    1. Re:Lock in from Microsoft by SL+Baur · · Score: 1

      if memcpy_s is part of the ANSI/ISO standard for C

      It's in an ISO standard - ISO/IEC TR 24731. Of course, the reputation and taste of ISO is kind of in question these days.

  72. , and will be replaced with... by Anonymous Coward · · Score: 0

    msmemcpy (TM), the proprietary alternative that is completely incompatible with any c/c++ standards, will only run on the MS platform, will have plenty of undocumented "features", and therefore at least as insecure as the original. Heck, we might even get another ISO norm out of it.

  73. Re:Let Java do it for you. by Lokitoth · · Score: 1

    Given that you do not know the size of the problem, claiming that any program that uses 8+ gigs of memory means that its programmers are incompetent shows a severe lack of foresight on your part. Unless of course you think 8GB should be enough for everyone.

  74. From TFA by Anonymous Coward · · Score: 0

    No need for everyone to freak out because functionality is going to disappear. From TFA:

    Developers who want to be SDL compliant will instead have to replace memcpy() functions with memcpy_s, a newer command that takes an additional parameter delineating the size of the destination buffer.

    So you're not really losing functionality, but the new API tries to cajole the developer into considering the size of the destination. And the old memcpy() will still be available, just considered unsafe.

  75. The goto threat == Raptors by beathach · · Score: 4, Funny

    Foolish mammal, they cannot be defeated so easily. http://xkcd.com/292/

  76. Solution! by bored · · Score: 1

    #define memcpy(a,b,c) memcpy_s(a,b,c,c)

    Chuckle....

    1. Re:Solution! by argent · · Score: 1

      That would be:

      #define memcpy(d,s,c) memcpy_s(d,c,s,c)

      I was going to say... if your memcpy is failing because you did not know how big the destination was, how does explicitly specifying the wrong size *twice* fix the problem?

  77. Idiocy by 12357bd · · Score: 1

    Let's also ban assembler code, fine, great!

    To ban a function is a symptom of idiocy, plain and simple.

    --
    What's in a sig?
  78. Comment removed by account_deleted · · Score: 1

    Comment removed based on user account deletion

  79. Re:Let Java do it for you. by Just+Some+Guy · · Score: 2, Insightful

    If you wrote a program that used 8+ gigs of memory that means you're an incompetent code monkey.

    I have an hourly job that processes about 8GB of input data files. We found that copying the data to a tmpfs filesystem instead of leaving it on a HDD cut the work time from 20 minutes to about 30 seconds because the job necessarily requires an enormous number of random seek()s. Since mmap()ing a file on tmpfs is roughly identical to read()ing the whole file into RAM, I guess that makes me an incompetent code monkey.

    Of course, my boss who got a 40x speedup in exchange for $250 worth of RAM might see things differently from your inexperienced little self. Sometimes the Real World throws pretty big datasets at you.

    --
    Dewey, what part of this looks like authorities should be involved?
  80. The creativity of the programmer? by caywen · · Score: 1

    What does this have to do with the creativity of the programmer? I can tell you right now that my creativity hits a brick wall when the code crashes down the line because I corrupted the stack after assuming my destination buffer is large enough to hold the specified number of bytes. If one doesn't know the size of the dest buffer before copying into it, maybe one should put creativity on hold for 2 minutes while one finds out.

  81. Another hand-holding mechanism by Anonymous Coward · · Score: 0

    Moves like this, plus the whole notion of managed code, automatic garbage collection, and other crap is to allow incompetent programmers to be able to write code. Most code additions like this that have been added in the last 20 years have created bloated, slow, and overly complex runtime systems that aren't really needed if you know what you're doing.

    "Real" software engineers don't need all this hand-holding. They don't need "training wheels" on their code.

    1. Re:Another hand-holding mechanism by petermgreen · · Score: 1

      that aren't really needed if you know what you're doing.
      Then either the majority of coders don't know what they are doing or even coders who do know what they are doing make mistakes occasionally (especially when tierd under pressure or similar).

      The fact is problems related to manual memory managements and bounds checking are among the most common types of security alert. Can you name a large and popular peice of software written in C that has never had a buffer overflow.

      --
      note: i'm known as plugwash most places but i screwd up registering that here somehow in the past and now can't register
  82. memcpy?? by nimbius · · Score: 1

    all i can think is this is whats best for...

    developers developers developers developers......

    --
    Good people go to bed earlier.
  83. Dammit its 1984 all over again! by Phizzle · · Score: 1

    What, too soon?

    --
    I will not be pushed, filed, stamped, indexed, briefed, debriefed or numbered. My life is my own.
  84. Unsafe by Anonymous Coward · · Score: 0

    C/C++ are fundamentally unsafe and should only be used by someone who knows what they are doing.
    Writing > 1 Million LOC in C++ you are bound to have serious memory problems.
    Passing size parameters only helps slightly.

    Runtime size checking is what is needed and is a much smarter solution.

  85. Exactly by Anonymous Coward · · Score: 0

    Of course it might be said that forcing the programmer to state it twice will (for low error incidence rates) half amount of bugs, this only applies when the probabilities are uncorrelated and I can see a problem looming right there. What they should have done is use C++'s type checking features to make sure that invalid copy operations simply don't compile. But that would have been way too practical. Also, what happened to "never postpone to runtime what you can do during compilation"? Catching bugs is nice and all, but wouldn't it be better to catch them before you ship? Nonetheless, banishing Memcpy is in itself a good idea and I think Microsoft does deserve some points for that.

  86. Re: Ada by darkwing_bmf · · Score: 1

    We use Ada for embedded code. It combines the power of C with the safety of ... Ada.

  87. Possible benefits by beej · · Score: 1

    I'm no fan of MS for a variety of reasons, but there are a couple things about these secure_s functions that are worthy of consideration.

    First of all, there's the explicit max-bytes-to-copy that's declared in memcpy_s(). Many people have pointed out that this is only as safe as you're trusting the programmer to be anyway, which is true to a certain extent, but it also calls on the coder to be acutely aware of the maximum buffer size.

    In this way, it makes the call safer against accidental overrun, and also against accidental overrun 5 years from now when an intern modifies the code as part of his or her code-familiarization project.

    This being said, I can also imagine people doing things like this:

    void dostuff(char *src, char *dest)
    {
          memcpy_s(dest, sizeof dest, src, strlen(src));
    }

    Yay! (That example could be worse, but could overrun dest for short buffers.)

    Secondly, the memcpy_s() function, like the rest of the _s functions, can invoke the "invalid parameter handler". This is a way to channel all your security violations into the same handler, which is rather nice in some ways. Instead of doing error checking all over (or failing to do error checking all over), you can have these things caught for you. IMHO, this feature is much more important than what you get from passing in the destSize.

    Here's my untested guess at the guts of the function (sans invalid parameter handler support):

    errno_t memcpy_s(void *dest, size_t numberOfElements, const void *src, size_t count)
    {
          if (count > numberOfElements) return errno = EINVAL;
          memcpy(dest, src, count);
          return 0;
    }

    I'm a little annoyed that "dest" is not returned like it is with memcpy(), but they probably don't want you to use it without testing it.

    One final thing that is irksome is that if this is supposed to be some kind of robust call, why does it still invoke undefined behavior for overlapping regions? Why not detect the overlap and return an error--or automagically switch to memmove_s()? Or just make memcpy_s() an alias for memmove_s()?

    I think I would assert that memcpy_s() will reduce the number of security defects. But I also think some percentage of the time it will be used incorrectly, and I don't know what that percentage is.

  88. Easy by Anonymous Coward · · Score: 0

    Stop using Visual Studio and go use a real toolchain.

  89. Seems a bit ridiculous by seandiggity · · Score: 1

    From the MSDN blog:
    If nothing else, memcpy_s makes you think about the size of the target buffer. . . Of course, you can easily make a call to memcpy_s() insecure by getting the buffer sizes wrong.

    I don't know a lot about C, but this seems a bit absurd to me. If a C programmer gets the target buffer size wrong with memcpy(), they're going to start being less sloppy with memcpy_s()?

    --
    Geeks like to think that they can ignore politics, you can leave politics alone, but politics won't leave you alone.-rms
  90. Re:Let Java do it for you. by Anonymous Coward · · Score: 0

    Good software doesn't force arbitrary limitations on the user. The user should only be limited by their hardware. So, if the algorithm requires reading the entire data set in at once, and the user has 8 GB of data, that program will use that much memory. In 10 years, 8 GB of memory will probably be considered small. If the program mistakenly enforced a memory limitation, it would have to be updated as hardware gets updated.

  91. C ivilizing C by happy_place · · Score: 1

    The change is no big deal, but I have to admit that as a C coder, I find the whole "need" to remove my ability to screw up my own programs... well... I dunno... It sorta robs the danger from the whole experience... How dare they civilize my C? :)

    --
    http://www.beanleafpress.com
  92. MS programmer fail by Anonymous Coward · · Score: 0

    see memcpy used incorrectly in Windows by typing

    calc /inp1111111111111111
    or
    calc /outp1111111111111111

    from 'Run' box or cmd prompt

    Fault found via a brute force prg I wrote. FWIW Brute force hacking trumps hacking by knowledge in that it is both thorough and complete.
    Neil

  93. advanced programmers... by Anonymous Coward · · Score: 0

    ... dont use microsoft products!

  94. Security Theater by woboyle · · Score: 1

    As Bruce Schneier would say, this is simply Security Theater. As others have pointed out, making ones code "compliant" is trivial, and worthless! As a professional, and published, software engineer with almost 30 years experience in the development of large-scale, high-availability distributed systems, I think that this is absurd in the extreme, and it takes focus away from techniques that can truly improve system reliability and security.

    --
    Sometimes, real fast is almost as good as real-time.
  95. Re:Let Java do it for you. by petermgreen · · Score: 1

    How hard is it to automatically translate C code to, say, C++/CLI?
    It's certainly doable for C and I can't see any reason why it wouldn't be for C++ too (though writing a correct C++ compiler targetting anything is a PITA afaict)

    http://cluecc.sourceforge.net/

    One thing I do find interesting is their benchmark results. translating C to java using thier tool (which is probablly not optimal) brings a pretty substantial performance penalty but the penalty for converting to java is far lower than the penalty for converting to any of the other managed languages they support.

    --
    note: i'm known as plugwash most places but i screwd up registering that here somehow in the past and now can't register
  96. properly written C++ does not use memcpy by master_p · · Score: 1

    That's a lower level function which is not normally used. Since std::vector is widely available, the need to use memcpy in C++ is minimal.

    1. Re:properly written C++ does not use memcpy by butlerm · · Score: 1

      Assuming your std::vector implementation doesn't slow your compile times down by a factor of ten and your run times by a factor of three, of course. The last time I tried GCC's C++ library, admittedly several years ago, things like basic_string were abysmally slow - so I wrote my own copy-on-write string library and have used it ever since. Perhaps the state of C++ standard library implementations has improved since then, but I have a twenty year history of writing my own class libraries that run circles around anything I have ever seen an out-of-the-box C++ standard library do.

      In my experience the world would be better off without the C++ standard library at all. In practice it is major step backward, to be avoided at all costs, a primary reason why C++ is relatively unpopular for general purpose programming, and so on.

    2. Re:properly written C++ does not use memcpy by gatkinso · · Score: 1

      Fool. Don't worry about us embedded developers who oftentimes need contiguously allocated storage and cannot have their storage fragmented all over fuck and dale.

      --
      I am very small, utmostly microscopic.
  97. from the libc expert by jjohn_h · · Score: 1

    *((char *) mempcpy (dst, src, n)) = '\0';

    1. Re:from the libc expert by Anonymous Coward · · Score: 0

      Incompetent bozo. mempcpy does not solve anything.

  98. Fool-proofing... by pive · · Score: 1

    Trying to fool-proof the C makes us neglect the more important task of C-proofing the fools. (Thanks jcr)

  99. Safe as in "Safe from people like YOU" by CarpetShark · · Score: 0

    But - what is "safe"?

    As others have pointed out, this is isn't about buffer overruns, as memcpy() takes a len argument. It's also not about safety. Type-safety makes sense, since memcpy() takes void pointers. But that makes much more sense in C# and (at a huge stretch) C++, than in C.

    I'm wondering if this has more to do with limiting programmers from doing interesting things like accessing raw memory addresses, bypassing DRM, etc.

    1. Re:Safe as in "Safe from people like YOU" by bluefoxlucid · · Score: 1

      I'm wondering if this has more to do with limiting programmers from doing interesting things like accessing raw memory addresses, bypassing DRM, etc.

      No you tin-foil retard, arbitrarily controlling one function that occurs in userland has nothing to do with DRM, since you can rewrite the function from scratch in 5 lines.

    2. Re:Safe as in "Safe from people like YOU" by CarpetShark · · Score: 1

      Immature AND using outdated information. Well done.

  100. Ban = operator also by Safiire+Arrowny · · Score: 2, Funny

    If a developer can't do "if (sizetocopy = sizeofdstbuffer)"

    Uh oh, we'd better ban the = operator too, so no one can mistake it for == in an if statement ever again.

    1. Re:Ban = operator also by prockcore · · Score: 1

      What's funny is that MS already did that.. you can't test for truth of a non boolean in C#.

      So unless sizetocopy is a boolean, the compiler will error out on that statement.

  101. missing the point by poor_boi · · Score: 1

    Everyone is claiming that developers will just turn this:
      memcpy(dst, src, size)
    into this:
      memcpy_s(dst, src, size, size);

    but for a large amount of MS code, this usage of memcpy_s is not advised and not common, and will be flagged in code review. So where does the size of the destination buffer come from if it is not simply a copy of the size of the src buffer? --> Often times the destination buffer, and indeed also the size of the destination buffer is passed in to your code by other code. In this case you simply and blindly pass the destination buffer and the size of the destination buffer into memcpy_s. In this case, allocation and size of the src buffer is something that your code determines, but the allocation and size of the dest buffer is not. You could say: well, should take into account the size of the destination buffer while allocating the source buffer -- to make sure the src buffer's size does not exceed that of the dst buffer you have been given. However, this is harder to audit. What memcpy_s does is, it joins more of the critical information about src and dst buffer sizes into a single line of auditable code.

    IMO this change doesn't necessarily it harder to write bad code, it just makes it easier to audit for and find bad code.

  102. Use GLib... by Tweenk · · Score: 1

    GLib has the functions g_sprintf, g_strdup, etc. which take care of allocating their own memory and are UTF-8 compliant. (You can replace the allocator if you wish.) The whole "size of buffer" problem does not exist when using GLib.

    --
    Those who would give up liberty to obtain working drivers, deserve neither liberty nor working drivers.
  103. Preprocessor FTW by Anonymous Coward · · Score: 0

    #define memcpy( dst, src, len ) memcpy_s( dst, len, src, len ) /* Fix't */

  104. Hmm, what about scatter/gather by Rene+S.+Hollan · · Score: 1

    You know, when you have a logically contiguous sequence of data items of a given type that are physically discontinuous and represented in their discontinuous form by an array of pointers to there representative parts and lengths?

    At some point you need a physically contiguous representation of them. Short of magical virtual memory hackery (which might work if the objects are of just the right size, and all aligned on just the right boundaries), you need a method to copy an specified block of contiguous objects from one location to some offset from another location.

    Not as type- and memory-unsafe as memcpy, but similar enough to get one into trouble, especially if the output size is not known at compile-time (which it most certainly won't be).

    A bounded memcpy, where the presumed extents of the sources and targets helps (and, IIRC is what MSFT now demands), but ultimately within it, a bald memcpy will be necessary for efficiency's sake.

    But, that can't be written.

    This is similar to the problem with "smart" pointers to reference-counted objects, that are destroyed and their memory reclaimed when the last reference to them disappears. At some implementation level, real, bald, pointers will have to be dealt with.

    This right solution here is to constrain where the tricky code lives and verify it more carefully than the "protected" code.

    --
    In Liberty, Rene
  105. This isn't about security, but vendor lock-in by mysidia · · Score: 1

    Their security assessments are troubling. memcpy() is generally pretty safe; you specify the number of bytes you are writing very explicitly.

    This is completely unlike strcat() or strcpy(). Memcpy is worlds apart from functions that blindly copy to a NUL, without requiring a length to be specified, I would agree that is indeed dangerous.

    Also, for inexplicable reasons, Strncpy(), Strncat(), and Snprintf() are on the list of banned functions. Although using these as safer alternatives to strcpy and friends IS a security best practice.

    Instead they recommend proprietary functions they have created, which are not part of the C standard.

    In other words, this is about forcing developers to use THEIR compiler and C libraries that provide these PROPRIETARY NON-STANDARD, NON-INTEROPERABLE functions... in the name of security.

    I applaud their efforts to improve security, but they as a compiler vendor should propose and STANDARDIZE the new functions, before introducing them to the C library and producing them as part of a "standard" C compiler.

    Until they do so, this is just another effort to lock developers in and expand and perpetuate their platform monopoly.

    You want to implement "Microsoft's best security practices?" Sure... and Develop multi-platform software utilizing the GCC C compiler or G++?

    Oh... SORRY, you can't do that.

  106. The cool thing... by FalseModesty · · Score: 1
    The cool thing about this discussion is how it highlights the brilliance of our slashdotty community. How many people here think "memcpy(dest, src, src_size)" is safe? How many people here think "memcpy(dest, src, dest_size)" is safe? They're both unsafe. memcpy_s() isn't much of an improvement, but at least it will overrun neither the source nor the destination (unless used very stupidly indeed).

    Nobody seems to have mentioned the other problem with memcpy(), which is that it only works on untyped data. This is always dangerous and rarely required.

  107. Ullirch needs to get off the Crack by CuteSteveJobs · · Score: 1

    > "That's definitely one of those notoriously dangerous C commands," said Johannes Ullrich, CTO of the SANS Institute, who teaches secure coding classes to developers. He likened memcpy() to other risky functions such as strcpy() and strcat(), which Microsoft has already banned after exacting untold misery over the years.

    These sound like the comments of a self-declared teacher rather than an actual programmer. I'm a C++ programmer and use memcpy() when I need to. If you're a decent programmer, it's not a problem. Bad programmers can write bad code regardless of what you give them. They can also write code that doesn't work, regardless of what tools they have. What's he going to do about that? What does he propose as an alternative? He sound re-read "Why Pascal isn't my favorite language", which addresses exactly this point. What else is Ullrich & co. going to "ban"? Pointers? C++ is used for game/system/real-time programming. You can't "ban" memcpy. Tell this guy to get a life and stop shilling his "institute", and someone send him "C++ for Dummies" too.

  108. If it's an array, you don't pass the size by mdwh2 · · Score: 1

    If this is done like their other *_s functions, then for arrays, you don't have to add an extra parameter. They provide templated versions that automatically know the size of the array, since it's known as compile time.

    Passing the extra parameter is only required when the size isn't known at compile time - in which cases, your laughable "MIN(sizeof(dst), bytes_to_copy)" would fail anyway.

    1. Re:If it's an array, you don't pass the size by ksheff · · Score: 1

      The templates only help when using C++, not the C projects that would also be affected by this change. You can laugh all you want, but MIN() still works if the programmer does his job by giving it the right input.

      --
      the good ground has been paved over by suicidal maniacs
  109. eh, I don't use memcpy, I use cpymem by Anonymous Coward · · Score: 0

    I hate to be the bearer of bad news to Microsoft (they're a great company after all...and helped computers move forward a bit), but the microsoft standard library is not the only way to copy memory. They can deprecate or disable calls to memcpy, but there are plenty of libraries out there that implement memcpy in ASM. There is no mandate in C programming that you use what comes with the standard c library.

  110. managed languages by rexguo · · Score: 1

    This is what managed languages are here to solve, so we can all write safer code without having to think too much about it.

    --
    www.rexguo.com - Technologist + Designer
  111. Any decent C programmer by Anonymous Coward · · Score: 0

    Any decent C programmer knows how to implement standard library functions. It's a pity that memcpy is at most a 3-liner.

    void *
    memcpy(void *s1, const void *s2, size_t n)
    {
            int i;
            for (i = 0; i n; ++i)
                    s1[i] = s2[i];
    }

  112. and next we banish compilers... by mt1955 · · Score: 1

    it would have been much cooler to think about limiting where memcpy can copy to

  113. Idiots. by Alex+Belits · · Score: 1

    This is an evidence that Microsoft lacks the most basic understanding what secure programming practices are.

    If you don't know why, please avoid touching a compiler for the rest of your life.

    --
    Contrary to the popular belief, there indeed is no God.
  114. Mixed views... by jschmerge · · Score: 2, Insightful
    I'm a C++ developer, and I'm mixed on this decision... On one hand, memcpy is a function that you can really hurt yourself with. On the other, it maps to extremely fast assembly that most processors can perform very quickly. There is a time & a place for everything. I think that a memcpy inside a class' constructor or assignment functions is perfectly acceptable, yet doing a memcpy(&destclass, &fromclass, sizeof(destclass)) is fundamentally dumb for more reasons than I care to illucidate (read one of Stroudstrup's or Meyer's books on C++ if you want to know). Doing something like that *really* demonstrates that you don't know the language.

    I guess Microsoft is trying to get people that don't understand C++ to program better in the language. IMHO, this will not solve fundamental problems with people programming C++, just cause them to learn the language slower by not having an experience working through a bastard of a bug. I think the world (and not just MS) needs to realize that writing a piece of complex software is difficult. Bugs like an errant memcpy of a subclass into a baseclass instance are *very* easy bugs to solve if you're looking for them. Memory overwrites are easy to detect if you are looking for them. Bad pointers are easy to detect if you're looking for them.

    Such problems will always exist in software. I've found a fair number in my own code. What we *really* need to do is train a better caliber of programmer. OTOH, Microsoft seems hell-bent on trying to make writing software easy to do

  115. memcpy is a compiler built-in by r00t · · Score: 1

    It's normal for a compiler to substitute 1 to 5 assembly instructions in place of a library call, especially if the number of bytes is known to be small. It runs faster.

    I'm thinking memcpy_s is a library call though. That makes it slower.

    1. Re:memcpy is a compiler built-in by TapeCutter · · Score: 1

      Yep it's probably implemented as an inline function for performnce but still at the C level it's a library call.

      --
      And did you exchange a walk on part in the war for a lead role in a cage? - Pink Floyd.
    2. Re:memcpy is a compiler built-in by GargamelSpaceman · · Score: 1

      In most cases speed is not a compelling reason - even at 'OS Level'. Premature optimization is the root of all evil even there. If speed is not obviously a compelling reason, then don't prematurely optimise for speed. Use performance profiling to optimize only where it actually helps. I think 'at OS Level' means it's easier for developers to hand wave about speed when there was really no compelling reason to make things complicated and/or error prone.

      --
      ...
  116. Making Incompetent Programmers by Anonymous Coward · · Score: 0

    Safeguarding potentially dangerous functions is what makes incompetent programmers, and limits the language beacuse of people who cant' use it well.

  117. Please ban them by Zoxed · · Score: 2, Interesting

    (I have 20+ years proffesional programming experience, a good chunk of it in C/C++, and in recent years have spent a lot of time debugging other peoples code, especially ported, re-ported and generally hacked around code !)

    IMHO a lot of the posts here are missing the point when they say, "these functions are safe, you just need to check the size before hand" etc. The fact is, in the Real World, not everyone is an ace-programmer, deadlines loom, mistakes get made. Problems do not appear in testing, but can further down the line. IMHO a language simply should *not allow* the programmer to do crazy things. Potential buffer overflows, de-referencing null pointers etc should not get past the *compiler*.

    To be honest I do not have a prefered language to suggest, but I do not think that tweaking C is the answer, but better, high level, languages are needed.

    1. Re:Please ban them by khuber · · Score: 2, Interesting

      Thank you for a sensible post. I agree that the only real solution has to be some abstraction or alternate mode for memory access that prevents the problem outright. C and C++ not only make it possible, but extremely easy to trash memory.

      The people claiming that the problem is programmers who are incompetent or stupid and believing that they are superhuman genius programmers who are somehow immune from errors are living under a delusion. You are not a beautiful and unique snowflake. We are all human and imperfect. I have seen many intelligent and competent programmers write incorrect code. I have personally written code with errors. We need to move beyond unproductive blame assigning mentalities to achieve real solutions or we will never be able to advance the state of software. Realistically, the prima donnas will continue on and other people will actually do something.

      memcpy_s is not a step forward for numerous reasons already mentioned. strncpy provides functionality that strcpy does not, namely a bound on its region of effect. memcpy was already bounded and neither memcpy_s or strncpy can prevent bad parameters from causing memory corruption. Hardware support like the NX/ED bits to mark pages as not executable are a good advancement on the security front, but still do not prevent data corruption. Complete removal of memory access like many languages do solves the problem with a high performance cost. Emerging techniques like STM may be able to incorporate data safety while maintaining hardware efficiency.

    2. Re:Please ban them by jonaskoelker · · Score: 1

      Potential buffer overflows, de-referencing null pointers etc should not get past the *compiler*.

      Note, however, that there's nothing stopping you from writing socket [...] system(recv()) if your language has sockets and the ability to run other programs.

      Some security problems arise not because you failed at expressing what you meant, but because you (probably unknowingly) meant the wrong thing.

      That being said,

      To be honest I do not have a prefered language to suggest

      Python does all your buffer work for you. It doesn't have null, although the None object acts kinda' like it. I'm sure similar things can be said about perl, ruby and shell scripts.

      But that's probably not the answer you wanted.

      I can also say good things about Haskell. It's a functional language similar to ML*. The type system forces you to be explicit about anything with side effects, in particular I/O. It doesn't have pointers (well, except behind the surface), so there are no nulls.

      There's an algebraic datatype called Maybe (taking a type parameter t) which can either be "No value" or "Some value of type t", so there's your null-equivalent. But---you have to be explicit about wanting a 'Maybe t' rather than just a 't', and the compiler warns you if you don't handle the no-value case (similar to C's switch/enum warning).

      The thing I like the most: even though you can violate the rules about being explicit about your side effects, the way to do it is by calling a function named unsafePerformIO. If you read the documentation of it (http://cvs.haskell.org/Hugs/pages/libraries/base/System-IO-Unsafe.html), you god damn know that you're being a naughty boy. And it's easy for your version control system to grep for this and automatically reject checkins using it ;-)

      * ML similarities: type inference, the type system, how algebraic data types work and look, syntax of function application (both partial and complete), lists are fairly important, has map/filter/reduce, you can define your own operators and their precedence.

  118. Question on tmpfs by drerwk · · Score: 1

    I've seen much discussion that with enough RAM and a smart kernel/fs, file access will be cached in RAM. Any idea why the fs you were using did not, but tmpfs did? Could it have been due to flush()? You managed a big win, so I am wondering is tmpfs just a bigger risk if ones system should go down?

    1. Re:Question on tmpfs by Just+Some+Guy · · Score: 1

      No, I really don't have any idea why it's not doing a better caching job, unless it has a substantially lower threshold for the amount of data it'll cache from one file (so as not to crowd out other processes with gigs of transient data). This is on FreeBSD 7-STABLE and a UFS2 filesystem, BTW. There isn't anything running on the machine that would be likely to flush() data with any regularity, ie no databases or anything.

      In a sense, I guess using TMPFS explicitly told the OS, "hey, I'm serious: keep this whole thing in RAM!" In our case, the whole process goes something like:

      1. Copy a file from the fileserver to a local filesystem.
      2. Process it and send the results to another machine.
      3. Delete the local copy.

      In the absolute worst case scenario with TMPFS and our setup, I'd lose the local copy that I'd just pulled off the fileserver. I can live with that risk. :-)

      --
      Dewey, what part of this looks like authorities should be involved?
  119. The dangers of strlen by AlastairLynn · · Score: 1

    I note they've also banned such wildly dangerous functions as strlen. What's even more interesting to me is that _INLINE ASM_ is perfectly acceptable under their guidelines, but not memcpy.

  120. Evaluating a macro argument twice = bad idea by rbarreira · · Score: 1

    You have just made a macro which evaluates one of its arguments twice. Very bad idea...

    Imagine someone writes:

    memcpy (ptr1, ptr2, size++);

    Demons will fly out of the user's nose.

    --

    The AACS key is NOT 0xF606EEFD628B1CA427BEA93A9CA9773F
  121. Cumulative lengths by Merdalors · · Score: 1
    To accomplish that, use:

    char *c, wk[512];
    c = wk;
    c += _snprintf(c, sizeof(wk) - (c - wk), "%s", someString);
    c += _snprintf(c, sizeof(wk) - (c - wk), "%s", someOtherString);
    ...
    etc

    --
    Slashdot entertains. Windows pays the mortgage.
  122. Stick a fork() in me, I'm done by notmebug · · Score: 1

    memcpy(flamewar, slashdot, all_your_base);

  123. Re: Just like microsoft by Douglas+Goodall · · Score: 1

    It is just like them to take something that is a standard and modify it in such a way that transportable software will not compile. They will not be happy until they get us all using their single source language technology and software will run only on Windows and impossible/impractical to port. They have been moving this way for years, what's new.

  124. Re:Let Java do it for you. by NoOneInParticular · · Score: 1

    Hey, you do realize that these days there's never an excuse to waste precious developer time on something as mundane as performance improvements, don't you? The TCO of the $250 worth of RAM is just a fraction of the gazzilion dollars it must have cost to have you automate the copying of the file to tmpfs. This is simply unacceptable: your boss should have to learn to live with dog-slow software just like everyone else!

  125. Doesn't get it by starfishsystems · · Score: 1

    I'm amazed at how persistently Microsoft doesn't get it.

    Look, here's how it works. The operating system protects processes from interfering with each other. This has been industry practice since the 1960's. The same concept extends to protecting users from each other and system resources from unprivileged access. The principle is called privilege containment.

    I appreciate that Microsoft has not, historically, seen fit to consider privilege containment when designing its operating systems. After all, it takes more programming effort, and a longer development cycle might cut into market share. Plus, as Bill Gates once explained to me, users didn't specifically ask for it. But on the other hand, it's very hard to build security into an insecure system, especially one whose functioning still relies on crazy stuff like executable content.

    So blame the victim. Encourage vendors to develop executable content, and encourage users to click on it. Make it everyone else's fault that the system doesn't itself provide the necessary protections. And just to underscore the abdication of responsibility, pop up lots and lots of confirmation windows so that there is no (legal) question that it was the user who made the choice. Remember, guns don't kill people, which is why it's okay to leave them firearms around ready to be discharged.

    In a saner, more conventional world, what processes do within their own address space is their own business. To think otherwise is to misunderstand the Halting Problem. We can certainly develop programming environments which do their own memory management, and that's great. Before Java there was Lisp. It's not a new idea. And it's a very useful idea, as far as it goes.

    Maybe we should ban C, is that the new idea? Who needs memcpy except someone who needs to do their own memory management? Indeed, someone who needs the freedom to program at a lower level than Java or Lisp, perhaps someone who is implementing an environment like Java or Lisp, extending PHP or Tcl/Tk, writing a protocol layer or a device driver or an embedded system, or doing any kind of fundamental operating system development.

    So rather than providing reasonable privilege containment so that those people can get on with their work, we'll just forbid the practice entirely. Or maybe we should just have lots and lots more popups? "Are you SURE that you want to use memcpy here?"

    --
    Parity: What to do when the weekend comes.
  126. Why do we care by Anonymous Coward · · Score: 0

    Why do we care what Microsoft dictates to it's followers? As programmers we have the choice to program what and how we want.